我试图从几篇文章中提取日期。当我测试正则表达式时,模式只匹配感兴趣的信息的一部分。如你看到的: https://regex101.com/r/ATgIeZ/2
这是文本文件的示例:
|[<p>Advertisement , By MILAN SCHREUER and ALISSA J. RUBIN OCT. 5, 2016
, BRUSSELS — A man wounded two police officers with a knife in Brussels around...] 3004
[<p>Advertisement , By DAVID JOLLY FEB. 8, 2016
, KABUL, Afghanistan — A Taliban suicide bomber killed at least three people on Mo JULY 14, 2034
我正在使用的提取模式和代码就是这个:
import re
text_open = open("News_cleaned_definitive.csv")
text_read = text_open.read()
pattern = ("[A-Z]+\.*\s(\d+)\,\s(\d+){4}")
result = re.findall(pattern,text_read)
print(result)
Anaconda的输出是:
[('5', '6'), ('7', '5'), ('1', '6'), .....]
预期输出为:
OCT. 5, 2016, FEB. 8, 2016, JULY 14, 2034 .....
答案 0 :(得分:1)
问题是重复命令<div class="row row-2">
<div></div>
<div></div>
</div>
<div class="row row-3">
<div></div>
<div></div>
<div></div>
</div>
<div class="row row-2">
<div></div>
<div></div>
</div>
,它位于您的最后一组之外。此外,捕获月份的正则表达式不在组中
修复如下:
{4}
您的数据样本的结果:
pattern = r"([A-Z]+)\.?\s(\d+)\,\s(\d{4})"
小额外修复:
[('OCT', '5', '2016'), ('FEB', '8', '2016'), ('JULY', '14', '2034')]
\.*
\.?
可能会发生)答案 1 :(得分:1)
感谢您的建议,它有助于理解正则表达式中括号的使用。 我用这个解决了自己:
pattern=("([A-Z]+\.*\s)(\d+)\,\s(\d{4})")