【发布时间】:2021-08-10 17:47:26
【问题描述】:
我是 python 新手,在获得正确的输出时遇到了问题。我有一个字符串列表:
list_string=[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
我想要的输出为:
Output expected: [['The course starts next Sunday'], ["I don't wash the dishes"], 'When does the train usually leave']
我所做的是:
import re
subtring='!DOC'
output=[]
for i in string:
if subtring in i:
text=re.findall("<p>(.*?)</t>",i, re.DOTALL)
output.append(text)
elif subtring in i:
text=re.findall("<d>(.*?)</span>",i, re.DOTALL)
output.append(text)
else:
output.append(i)
print (output)
[['The course starts next Sunday'], ["class='default'<d>I don't wash the dishes</span>"], 'When does the train usually leave']
任何人都可以提出正确的方法吗?
【问题讨论】:
-
为什么你有两个
subtring in i测试?第二个永远不会成功。 -
为什么要使用第二个正则表达式而不是第一个来处理第二个字符串?
-
在同一个
if块中执行两者。 -
我不明白你的逻辑。第二个字符串匹配两个正则表达式。为什么输出应该包含来自第二个
findall而不是第一个的结果? -
如何知道从结果中排除
class='default'?
标签: arrays python-3.x regex