Python 在Findall中添加OR条件,Lxml
我有以下findall表达式:Python 在Findall中添加OR条件,Lxml,python,xml,python-2.7,lxml,findall,Python,Xml,Python 2.7,Lxml,Findall,我有以下findall表达式: for r in p.findall('.//r'): for a in r.findall('.//br'): text+= " " for c in r.findall('.//tab'): text+= " " 如果遇到标签“br”或“tab”,我想在文本变量中添加一个空格,但我想使用一个表达式,而不是两
for r in p.findall('.//r'):
for a in r.findall('.//br'):
text+= " "
for c in r.findall('.//tab'):
text+= " "
如果遇到标签“br”
或“tab”
,我想在文本变量中添加一个空格,但我想使用一个表达式,而不是两个单独的表达式。比如:
for a in r.findall('.//br'|'.//tab'):
但这将返回一个不受支持的操作数类型错误
TypeError: unsupported operand type(s) for |: 'str' and 'str'
正确的语法是什么?代码对两个字符串操作数使用
|
运算符
>>> 'a' | 'b'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
如果要使用
findall
,请将两个列表连接为一个列表并进行迭代:
for a in r.findall('.//br') + r.findall('.//table'):
或使用:
是否可以使用findall???@Swordy,
findall
不支持完整的XPath表达式。您可以将findall
与pythonif
语句结合起来,但它更为冗长。@Swordy,这个怎么样<代码>对于r.findall('.//br')+r.findall('.//table')中的a:…太棒了,这一个有效了。。!!就计算时间而言,这是等同于我的表达式,还是更快???@Swordy,我不确定。你自己动手做怎么样。
for a in r.findall('.//br') + r.findall('.//table'):
import itertools
for a in itertools.chain(r.findall('.//br'), r.findall('.//table')):