陈腔滥调

2024-04-19 22:22:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在pandas dataframe中保存一个陈词滥调的列表,并希望在文本文件中运行它并找到extact匹配项。有可能使用spaCy吗?在

熊猫标本清单。在

Abandon ship
About face
Above board
All ears

例句。在

^{pr2}$

预期产量:

abandon ship
all ears

它必须考虑列表和句子之间的大小写敏感度。在

目前我正在使用这种方法来实现单字匹配。在

Column compare and return values

pd.DataFrame([np.intersect1d(x,df1.WORD.values) for x in df2.values.T],index=df2.columns).T

Tags: dataframepandas列表spacyabovefaceaboutvalues
1条回答
网友
1楼 · 发布于 2024-04-19 22:22:28

您正在寻找Spacy的matcher,您可以阅读关于here的更多信息。它可以为您找到任意长/复杂的令牌序列,并且您可以轻松地将其并行化(参见pipe()的matcher文档)。它默认返回文本中匹配项的位置,尽管您可以使用找到的标记执行任何操作,还可以添加一个on_match回调函数。在

也就是说,我认为你的用例相当简单。我已经包括了一个例子,让你开始。在

import spacy
from spacy.matcher import Matcher

nlp = spacy.load('en')

cliches = ['Abandon ship',
'About face',
'Above board',
'All ears']

cliche_patterns = [[{'LOWER':token.text.lower()} for token in nlp(cliche)] for cliche in cliches]

matcher = Matcher(nlp.vocab)
for counter, pattern in enumerate(cliche_patterns):
    matcher.add("Cliche "+str(counter), None, pattern)

example_1 = nlp("Turn about face!")
example_2 = nlp("We must abandon ship! It's the only way to stay above board.")

matches_1 = matcher(example_1)
matches_2 = matcher(example_2)

for match in matches_1:
    print(example_1[match[1]:match[2]])

print("    ")
for match in matches_2:
    print(example_2[match[1]:match[2]])

>>> about face
>>>     
>>> abandon ship
>>> above board

只需确保您有Spacy(2.0.0+)的最新版本,因为matcher API最近发生了更改。在

相关问题 更多 >