正则表达式 |从文本中提取日期
Regular expressions | Extracting dates from text
我正在尝试从多篇文章中提取日期。当我测试正则表达式时,模式只匹配部分感兴趣的信息。如你看到的:
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 .....
问题是重复命令 {4}
在您的最后一组之外。此外,捕获月份的正则表达式不在组内
像这样修复它:
pattern = r"([A-Z]+)\.?\s(\d+)\,\s(\d{4})"
您的数据样本的结果:
[('OCT', '5', '2016'), ('FEB', '8', '2016'), ('JULY', '14', '2034')]
额外的小修复:
- 可以有0个或1个点。因此为
\.?
删除了 \.*
- 使用 "raw" 前缀,在定义正则表达式字符串时总是更好(这里没有问题,但例如
\b
可能会发生)
感谢您的建议,它有助于理解括号在正则表达式中的使用。
我用这个解决了自己:
pattern=("([A-Z]+\.*\s)(\d+)\,\s(\d{4})")
我正在尝试从多篇文章中提取日期。当我测试正则表达式时,模式只匹配部分感兴趣的信息。如你看到的: 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 .....
问题是重复命令 {4}
在您的最后一组之外。此外,捕获月份的正则表达式不在组内
像这样修复它:
pattern = r"([A-Z]+)\.?\s(\d+)\,\s(\d{4})"
您的数据样本的结果:
[('OCT', '5', '2016'), ('FEB', '8', '2016'), ('JULY', '14', '2034')]
额外的小修复:
- 可以有0个或1个点。因此为
\.?
删除了 - 使用 "raw" 前缀,在定义正则表达式字符串时总是更好(这里没有问题,但例如
\b
可能会发生)
\.*
感谢您的建议,它有助于理解括号在正则表达式中的使用。 我用这个解决了自己:
pattern=("([A-Z]+\.*\s)(\d+)\,\s(\d{4})")