我正在使用正则表达式来匹配以“ Dr.”开头的名称。但是,当我打印火柴时,它们将打印为列表,有些是空的。我想只打印名称。
码:
import re
f = open('qwert.txt', 'r')
lines = f.readlines()
for x in lines:
p=re.findall(r'(?:Dr[.](\w+))',x)
q=re.findall(r'(?:As (\w+))',x)
print p
print q
qwert.txt:
Dr.John and Dr.Keel
Dr.Tensa
Dr.Jees
As John winning Nobel prize
As Mary wins all prize
car
tick me 3
python.hi=is good
dynamic
and precise
tickme 2 and its in it
its rapid
its best
well and easy
所需的输出:
John
Keel
Tensa
Jees
John
Mary
实际输出:
['John', 'Keel']
[]
['Tensa']
[]
['Jees']
[]
[]
['John']
[]
['Mary']
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
最佳答案
您看到的[]
是因为findAll
返回字符串的list
。如果您本身需要字符串,请遍历findAll的结果。
p=re.findall(r'(?:Dr[.](\w+))',x)
q=re.findall(r'(?:As (\w+))',x)
for str in p+q:
print str
关于python - python打印正则表达式匹配产生空列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24843768/