【问题标题】:getting an exact match from a list in python从python中的列表中获取完全匹配
【发布时间】:2020-05-03 04:11:57
【问题描述】:

我正在尝试从文本块中提取名称,因为只有很少的名称可以出现,所以很容易预先构建名称列表,我想在文本中匹配它们。例如,我有以下列表:

names = [ "Wim Duisenberg", "Jean-Claude Trichet", "Mario Draghi", "Christine Lagarde"]

以及通过美丽的汤刮掉的以下文本块:

print(textauthors)
<h2 class="ecb-pressContentSubtitle">Mario Draghi, President of the ECB, <br/>Vítor Constâncio, Vice-President of the ECB, <br/>Frankfurt am Main, 20 October 2016</h2>

我尝试了以下解决方案(基于this 对堆栈溢出的回答):

def exact_Match(textauthors, names):
b = r'(\s|^|$)' 
res = return re.match(b + word + b, phrase, flags=re.IGNORECASE)
print(res)

它给了我一个语法不正确的错误,我不知道如何解决它。如果在堆栈溢出的某个地方已经有这个问题的答案,也让我提前道歉,我是 python 初学者,我不确定如何搜索正确的问题。当我搜索名称匹配时,我看到尝试使用 nltk 进行匹配的答案,但这并不适合我想要获得完全匹配的地方,当我尝试根据字符串文本搜索匹配时,我找不到答案对我有用。

【问题讨论】:

  • 语法错误应该准确指出问题所在:res = return &lt;somethign&gt; 没有意义。分配或返回。
  • 此外,您可能不应该直接对 HTML 使用正则表达式。
  • @WiktorStribiżew 我实际上发现了这个问题,但它对我没有用。也许是因为它使用了 python 2 而我使用了 3,或者是因为我错过了那里的代码。在这篇文章之前,我实际上尝试了很多其他 SE 答案。但如果您认为这仍然是重复的,请投票关闭它。
  • Python 3 的解决方案也是如此。见ideone.com/zUTj2o

标签: python regex text match


【解决方案1】:

这将为您提供来自 textauthors 的作者:

import re

textauthors = '<h2 class="ecb-pressContentSubtitle">Mario Draghi, President of the ECB, <br/>Vítor Constâncio, Vice-President of the ECB, <br/>Frankfurt am Main, 20 October 2016</h2>'
regex = r">(?P<name>[^\s]+\s[^\s]+),"
matches = re.findall(regex, textauthors)
print(matches) # ['Mario Draghi', 'Vítor Constâncio']

当然,如果您需要从 textauthors 中提取作者

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 2019-11-30
    相关资源
    最近更新 更多