【发布时间】:2021-11-16 16:08:34
【问题描述】:
我正在尝试从 Outlook“to”约定中的字符串解析名称和姓氏的所有实例,并将每个实例保存在 python 列表中。我正在使用 Python 3.6.4。
例如,我想要以下字符串:
“致:约翰·列侬
\b002; Paul McCartney \b002;"
要解析成:
['约翰列侬','保罗麦卡特尼']
我使用Replace all words from word list with another string in python作为参考,并想出了这个代码:
import re
prohibitedWords = [r'to:',r'To:','\b002',"\<(.*?)\>"]
mystring = 'To: John Lennon <John.Lennon@gmail.com> \b002; Paul McCartney <Paul.McCartney@yahoo.com> \b002;'
big_regex = re.compile('|'.join(prohibitedWords))
the_message = big_regex.sub("", str(mystring)).strip()
print(the_message)
但是,我得到以下结果:
John Lennon ; Paul McCartney ;
这不是最优的,因为我得到了很多我无法解析的空间。此外,我觉得这不是最佳方法。
感谢任何建议。
谢谢
【问题讨论】:
-
也许使用
re.findall('(?:\\bto:|\b002;)\s*(.*?)\s*<', mystring, re.I)?