在我的Python
代码中,我有一个字符串,并试图查找该字符串是否包含特定的模式(名称后面是数字)。为此,我使用re.match
然后groups()
它来获得这样的所需结果
authors_and_year = re.match('(.*)\. (\d{4})\.', line)
texts, authors, year = authors_and_year.groups()
如果我有一根这样的线
Regina Barzilay and Lillian Lee. 2004. Catching the drift: Probabilistic content models, with applications to generation and summarization. In Proceedings of NAACL-HLT.
它将返回我这个(如预期的那样)
('Regina Barzilay and Lillian Lee. 2004.', 'Regina Barzilay and Lillian Lee', '2004')
但在某些情况下,我有这样的字符串
J. Cohen. 1968a. Weighted kappa: Nominal scale agreement with provision for scaled disagreement or partial credit. volume 70, pages 213–220
或者这个,
Ralph Weischedel, Jinxi Xu, and Ana Licuanan. 1968b. A hybrid approach to answering biographical questions. In Mark Maybury, editor, New Directions In Question Answering, chapter 5. AAAI Press
当年份有字母表时,因此上层正则表达式在这里失败。为了处理这个场景,我尝试添加一个新的正则表达式,如下所示
authors_and_year = re.match('((.*)\. (\d{4})\.|(.*)\. (\d{4})(a-z){1}\.)', line)
texts, authors, year = authors_and_year.groups()
但它给了我这个错误
ValueError: too many values to unpack (expected 3)
当我检查authors_and_year
值时,它是这样的
('Regina Barzilay and Lillian Lee. 2004.', 'Regina Barzilay and Lillian Lee', '2004', None, None, None)
我不知道最后3None
个值是从哪里来的。谁能告诉我我做错了什么
这就是团队处理
|
的方式None
来自第二种选择。见:您可以筛选出不匹配项:
或者,您可以使用命名组:
如果可能存在空匹配(组=空字符串),则此代码将不起作用;你需要做一些类似的事情
您的正则表达式可以简化为
((.*)\.[ ](\d{4})[a-z]?\.)
这使得年后的字母是可选的,同时保留3个捕获组
相关问题 更多 >
编程相关推荐