我有一个包含如下条目的文本文件:
@markwarner VIRGINIA - Mark Warner
@senatorleahy VERMONT - Patrick Leahy NO
@senatorsanders VERMONT - Bernie Sanders
@orrinhatch UTAH - Orrin Hatch NO
@jimdemint SOUTH CAROLINA - Jim DeMint NO
@senmikelee UTAH -- Mike Lee
@kaybaileyhutch TEXAS - Kay Hutchison
@johncornyn TEXAS - John Cornyn
@senalexander TENNESSEE - Lamar Alexander
我编写了以下内容以使用正则表达式删除“否”和破折号:
import re
politicians = open('testfile.txt')
text = politicians.read()
# Grab the 'no' votes
# Should be 11 entries
regex = re.compile(r'(no\s@[\w+\d+\.]*\s\w+\s?\w+?\s?\W+\s\w+\s?\w+)', re.I)
no = regex.findall(text)
## Make the list a string
newlist = ' '.join(no)
## Replace the dashes in the string with a space
deldash = re.compile('\s-*\s')
a = deldash.sub(' ', newlist)
# Delete 'NO' in the string
delno = re.compile('NO\s')
b = delno.sub('', a)
# make the string into a list
# problem with @jimdemint SOUTH CAROLINA Jim DeMint
regex2 = re.compile(r'(@[\w\d\.]*\s[\w\d\.]*\s?[\w\d\.]\s?[\w\d\.]*?\s+?\w+)', re.I)
lst1 = regex2.findall(b)
for i in lst1:
print i
当我运行代码时,它会捕获除了 Jim DeMint 的姓氏之外的 twitter 句柄、状态和全名。我已经说过我想忽略正则表达式的大小写。
有任何想法吗?为什么表达式没有捕捉到这个姓氏?