[英]Adding an OR condition in Findall, Lxml
I have the following findall expression : 我有以下findall表达式:
for r in p.findall('.//r'):
for a in r.findall('.//br'):
text+= " "
for c in r.findall('.//tab'):
text+= " "
And i want to add a space in the text variable if i come across the tag "br"
or "tab"
, but I want to use a single expression rather than 2 separate ones. 而且,如果我遇到标签
"br"
或"tab"
,我想在文本变量中添加一个空格,但是我想使用一个表达式而不是两个单独的表达式。 something like: 就像是:
for a in r.findall('.//br'|'.//tab'):
but this returns an unsupported operand type error. 但这会返回不受支持的操作数类型错误。
TypeError: unsupported operand type(s) for |: 'str' and 'str'
What is the right syntax for this? 正确的语法是什么?
The code is using |
该代码正在使用
|
operator for two string operands. 两个字符串操作数的运算符。
>>> 'a' | 'b'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
Specify |
指定
|
inside the string literal. 在字符串文字中。 And use
xpath
method : 并使用
xpath
方法 :
for a in r.xpath('.//br|.//tab'):
If you want to use findall
, concatenate two list into one and iterate it: 如果要使用
findall
,请将两个列表连接成一个列表并对其进行迭代:
for a in r.findall('.//br') + r.findall('.//table'):
or using itertools.chain
: 或使用
itertools.chain
:
import itertools
for a in itertools.chain(r.findall('.//br'), r.findall('.//table')):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.