【问题标题】:Multiple regex patterns to extract data from article using python使用 python 从文章中提取数据的多个正则表达式模式
【发布时间】:2018-10-03 00:08:12
【问题描述】:

python 新手,但生活却老了。 我尝试使用 txt 文件中的多个正则表达式模式从新闻文章 txt 文件中提取数据。我已经达到了可以找到匹配项但无法保存提取数据的地步。到目前为止,这就是我在原始不卫生的非 Python 脚本中所拥有的。我感谢所有的 cmet,因为我正在自学。

import re

reg_ex = open('APT1.txt', "r", encoding = 'utf-8-sig')
lines = reg_ex.read()
strip = lines.strip()
reggie = strip.split(';') 


reggie_lst = []
match_lst = []

for raw_regex in reggie:
    reggie_lst.append(re.compile(raw_regex))


get_string = open("APT.txt", "r", encoding = 'utf-8-sig')
nystring = get_string.read()


if any(compiled_reg.search(nystring) for compiled_reg in reggie_lst):
    print("Got some Matches")

【问题讨论】:

  • 你想提取什么?列表中所有正则表达式的所有匹配项?如果您提供一个简单的示例和预期的结果会更好。另外,请说明您要问的问题是什么。
  • 坐在一个循环中,就像编译的正则表达式上的一个 for 循环。使用正则表达式和输入做某种查找。因此,每次传递都会获得一些数据数组,您可以将它们保存到永久位置。
  • 抱歉不清楚。我想从 APT.txt 文件中的文章中提取所有匹配项。我在问如何捕获这些数据(匹配单词列表)并将其放入另一个 txt 文件中。这些词将是词的精确词和派生词。

标签: python regex


【解决方案1】:

您可以使用re.findall() 将您的数据提取到一个列表中,而不仅仅是询问正则表达式是否匹配。

import re

reg_ex = open('APT1.txt', "r", encoding='utf-8-sig')
lines = reg_ex.read()
strip = lines.strip()
reggie = strip.split(';')

reggie_lst = []
match_lst = []

for raw_regex in reggie:
    reggie_lst.append(raw_regex)

get_string = open("APT.txt", "r", encoding='utf-8-sig')
nystring = get_string.read()


for reg in reggie_lst:
    for text_match in re.findall(reg, nystring):
        print("Got match for regex {}: {}".format(reg, text_match))

当然,您也可以将其保存在新文件中,而不是在最后一行打印。在此示例中,我还删除了仅为打印/调试目的编译正则表达式。

在您的正则表达式中使用括号(组)时要小心。 re.findall() 的行为与 re.search()re.match() 有点不同。然后你必须使用(?: …,另见this post

【讨论】:

  • 谢谢。我还有很长的路要走,还有很多阅读要做。这让我超越了一个症结所在。非常感谢。
猜你喜欢
  • 2013-04-04
  • 2017-02-28
  • 2021-06-27
  • 2015-11-21
  • 2013-12-18
  • 2011-04-21
  • 1970-01-01
  • 2019-05-13
相关资源
最近更新 更多