我正在尝试使用Python 2.7.2中的正则表达式从字符串中提取所有标记词的出现次数。或者简单地说,我想提取在[p]
和[/p]
标记中的每一个文本片段。
这是我的尝试:
regex = ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person = re.findall(pattern, line)
打印person
会产生['总统[P]', '[/P]', '[P]比尔·盖茨[/P]']
正确的正则表达式是什么,以获得:['[P]巴拉克·奥巴马[/P]', '[P]比尔·盖茨[/P]']
或['巴拉克·奥巴马', '比尔·盖茨']
。
在这里,re.findall()会返回一个包含所有找到的电子邮件字符串的列表
emails = re.findall(r'[\w.-]+@[\w.-]+', str) ## ['alice@google.com', 'bob@abc.com']for email in emails: # 对每个找到的电子邮件字符串进行操作 print email - kkron