【问题标题】:Python: difflib.get_close_matches comparing modified text but returning originalPython:difflib.get_close_matches 比较修改后的文本但返回原始文本
【发布时间】:2021-01-13 13:01:41
【问题描述】:

我从文本中提取了一个单词列表,但在文本预处理期间,我将所有内容都小写了以便于比较。

我的问题是如何使列表中提取的单词与原文中的完全一致?

我尝试首先对原始文本进行标记,然后在此标记列表中找到与我从文本中提取的单词列表最接近的匹配项。我使用以下各项来查找最接近的匹配项:

  1. nltk.edit_distance
  2. difflib.get_close_matches

但它们都没有按我的意愿工作。他们提取了某种相似的词,但并不完全像它们在原始文本中出现的那样。我认为问题在于这些方法对小写和大写单词的处理方式不同。

提取的单词可以是一元、二元,最高可达 5-gram。

例子:

我从文本 [rfid alert] 中提取了以下二元组,但在原始文本中它看起来像这样 [RFID alert]

使用后

difflib.get_close_matches('rfid alert', original_text_unigram_tokens_list)

它的输出是 [profile Caller] 而不是 [RFID alert]。那是因为 python 是区分大小写的。我认为它发现original_text_unigram_tokens_list 中与 [rfid alert] 不同字符数量最少的二元组是 [profile Caller] 所以它返回 [profile来电者]

因此我的问题是:是否有任何现成的方法或任何解决方法可以返回原始形式的 ngram,因为它完全出现在文本中?例如,我想获得 [RFID alert] 而不是上面示例中的 [profile Caller],依此类推。

感谢您的帮助。提前谢谢你。

【问题讨论】:

  • 能否提供一些例子(数据)?
  • 抱歉没有举个例子。我已经更新了我的问题以包含一个清晰的示例。如果上面的例子不够清楚,你可以告诉提供更多的例子。谢谢你。 @sophros

标签: python nlp data-analysis data-cleaning difflib


【解决方案1】:

类似于this question,您可以获取和修改difflib.get_close_matches 的源代码,并根据您的需要进行调整。

我所做的修改:

  • cutoff 默认值提高到 0.99(理论上它甚至可以是 1.0,但为了确保数值错误不影响结果,我传递了一个较小的数字)。

  • s.set_seq1(x.lower()) - 以便在小写字符串之间进行比较(但返回原始x

修改函数的完整代码:

from difflib import SequenceMatcher, _nlargest  # necessary imports of functions used by modified get_close_matches

def get_close_matches_lower(word, possibilities, n=3, cutoff=0.99):
    if not n >  0:
        raise ValueError("n must be > 0: %r" % (n,))
    if not 0.0 <= cutoff <= 1.0:
        raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
    result = []
    s = SequenceMatcher()
    s.set_seq2(word)
    for x in possibilities:
        s.set_seq1(x.lower())  # lower-case for comparison
        if s.real_quick_ratio() >= cutoff and \
           s.quick_ratio() >= cutoff and \
           s.ratio() >= cutoff:
            result.append((s.ratio(), x))

    # Move the best scorers to head of list
    result = _nlargest(n, result)
    # Strip scores for the best n matches
    return [x for score, x in result]

你给出的例子的结果:

print(get_close_matches_lower('rfid alert', ['profile Caller','RFID alert']))

印刷:

['RFID alert']

【讨论】:

  • 我真的非常感谢你对这个功能的巨大修改。当我测试它时,这个功能真的很适合我。但我认为由于我的文本中的一些文本清理问题,有时我需要将截止值更改为 0.6 而不是 0.99 以避免函数返回空列表的情况,它做得非常好并获得了匹配。再次感谢你。 @sophros
  • @Bahgat - 很高兴听到并乐于提供帮助。您能否通过单击我的答案旁边的灰色刻度线将问题标记为已回答?非常感谢。
  • 谢谢你的提醒。当然,我现在做到了。再次非常感谢您的大力帮助。 @sophros
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多