如何在文本中搜索可能在文本中分隔的复合短语;在python中?



>假设我有一个文本,想要检查它是否包含一些复合短语,其中我还想包括各个单词可能不直接相互跟随的情况。

例如,假设您要检查文本是否是关于消防员的,那么像这样的文本

text = "currently there are over 4000 people involved in fighting the rapidly growing fires in Australia"

也应该产生积极的结果。(我实际上想将其应用于德语,其中示例可能不那么人为(

我没有NLP方面的专业知识,所以也许有一些聪明的方法可以做到这一点,我只是不知道要搜索的正确术语。 当然,如果文本不是太大,可以对所有 2 个单词的组合进行以下详尽搜索:

import itertools
import spacy
nlp = spacy.load({model})
doc = nlp(text)
wordlist =[t.lemma_ for t in doc if (not t.is_punct and not t.is_stop and not t.is_digit)]
combs = itertools.combinations(wlist,2)
comb_set = [set(c) for c in combs]
{'fire','fight'} in comb_set

但我在想,可能有一种更有效的方法可以做到这一点。

如果您只想检查文本中是否存在引理"火"和"战斗",那么与其显式生成所有组合(二次复杂度(,不如检查这些引理是否都属于所有引理的集合(线性复杂度(:

# !python -m spacy download en_core_web_sm
import spacy
nlp = spacy.load('en_core_web_sm')
text = "currently there are over 4000 people involved in fighting the rapidly growing fires in Australia"
doc = nlp(text)
lemmas = {token.lemma_ for token in doc}
print('fire' in lemmas and 'fight' in lemmas) # True

您可能还需要检查单词"火"和"战斗"是否直接相关 - 这样您的规则就不会在文本"我点火并观看烟雾与蚊子打架"上激活。

您可以通过检查单词"战斗"是否是单词"火"的句法头来实现此目的。这个测试在复杂性上也是线性的(如果句法解析器是线性的,就像在空间中一样(,所以它应该很好地扩展到大文本。

def check_phrase(text, head, child):
return any((t.lemma_ == child and t.head.lemma_ == head) for t in nlp(text))
text = "currently there are over 4000 people involved in fighting the rapidly growing fires in Australia"
print(check_phrase(text, 'fight', 'fire'))  # True
another_text = "I light the fire and watch the smoke fight with the mosquitoes"
print(check_phrase(another_text, 'fight', 'fire'))  # False

最新更新