我正在使用正则表达式来匹配以“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
