Excel 列表中的短语匹配

问题描述 投票:0回答:1

我得到了一个 Excel 数据库,其中包含两列陈词滥调短语和类型。我需要检查文本文档中短语的精确匹配并返回匹配短语的类型。也最好用红色字体匹配原始文档中的短语。我的兴趣是识别文本文件中的类型并返回类型。

目前识别陈词滥调的短语,但卓越的工作却让我困惑。

import spacy
from spacy.matcher import Matcher

nlp = spacy.load('en_core_web_sm')

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_2 = nlp("We must abandon ship! It's the only way to stay above board.")
matches_2 = matcher(example_2)
for match in matches_2:
    print(example_2[match[1]:match[2]])

MRE:

模拟文字:

两个精致的反对意见令人高兴,虽然有缺陷,但已包含在内。亲切是因为其主题显而易见而吃。能否正确跟随学习,让你对他有所怀疑。很多我们善良的女士的脚都这么问。费自己适度的日子胖了一点,先生的家庭感情更强了。你不能通过封面来判断一本书本身跳出框框思考,答案总是埃克塞特这样做。虽然还是我很不安。如此看来,友谊非常关乎感情。提提更大的十五一诺言,因为也没有。为什么 蠕虫罐头 表示说话的脂肪沉迷于看到住宅的嘲笑。

预期输出:

Type A
Type B
pandas nltk spacy
1个回答
0
投票

对陈词滥调匹配方面的代码进行了一些细微的更改。这会将陈词滥调的类型写入不带颜色的

txt
文件:

import spacy
from spacy.matcher import Matcher
from openpyxl import load_workbook

nlp = spacy.load('en_core_web_sm')

wb = load_workbook('cliche_phrases.xlsx')
ws = wb.active
cliche_database = {row[0].lower(): row[1] for row in ws.iter_rows(min_row=2, values_only=True)}

cliches = list(cliche_database.keys())

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

matcher = Matcher(nlp.vocab)

matcher.add("Cliche", cliche_patterns)

# Read and process the mock text
with open('mock_text.txt', 'r') as file:
    text = file.read()

doc = nlp(text)
matches = matcher(doc)

cliche_types_output = []
for match_id, start, end in matches:
    cliche_phrase = doc[start:end].text
    cliche_type = cliche_database.get(cliche_phrase)
    
    if cliche_type:
        cliche_types_output.append(cliche_type)

output_filename = 'output.txt'
with open(output_filename, 'w') as output_file:
    output_file.write("\n".join(cliche_types_output))

我将更新答案以包括匹配单词的颜色。

© www.soinside.com 2019 - 2024. All rights reserved.