簡體   English   中英

在Findall,Lxml中添加OR條件

[英]Adding an OR condition in Findall, Lxml

我有以下findall表達式:

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'

指定| 在字符串文字中。 並使用xpath方法

for a in r.xpath('.//br|.//tab'):

如果要使用findall ,請將兩個列表連接成一個列表並對其進行迭代:

for a in r.findall('.//br') + r.findall('.//table'):

或使用itertools.chain

import itertools

for a in itertools.chain(r.findall('.//br'), r.findall('.//table')):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM