在python中从单词包中搜索文本

2024-09-28 22:24:10 发布

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

假设我有一包关键词。 例如:

['profit low', 'loss increased', 'profit lowered']

我有一个pdf文档,我从中解析整个文本, 现在我想得到与这袋单词相匹配的句子。你知道吗

假设一句话是:

'The profit in the month of November lowered from 5% to 3%.'

这应该匹配,因为在单词包中'profit lowered'匹配这个句子。你知道吗

用python解决这个问题的最佳方法是什么?你知道吗


Tags: thein文档文本pdf单词关键词句子
3条回答
# input
checking_words = ['profit low', 'loss increased', 'profit lowered']
checking_string = 'The profit in the month of November lowered from 5% to 3%.'

trans_check_words = checking_string.split()
# output
for word_bug in [st.split() for st in checking_words]:
    if word_bug[0] in trans_check_words and word_bug[1] in trans_check_words:
        print(word_bug)

您可以尝试以下操作:

将一袋单词转换成一个句子:

bag_of_words = ['profit low', 'loss increased', 'profit lowered']    
bag_of_word_sent =  ' '.join(bag_of_words)

然后是句子列表:

list_sents = ['The profit in the month of November lowered from 5% to 3%.']

使用Levenshtein距离:

import distance
for sent in list_sents:
    dist = distance.levenshtein(bag_of_word_sent, sent)
    if dist > len(bag_of_word_sent):
        # do something
        print(dist)

如果你的检查单词列表元素在长句中,你需要检查它

sentence = 'The profit in the month of November lowered from 5% to 3%.'

words = ['profit','month','5%']

for element in words:
    if element in sentence:
        #do something with it
        print(element)

如果您想更清楚,可以使用此单行循环将匹配的单词收集到列表中:

sentence = 'The profit in the month of November lowered from 5% to 3%.'

words = ['profit','month','5%']

matched_words = [] # Will collect the matched words in the next life loop:

[matched_words.append(word) for word in words if word in sentence]

print(matched_words)

如果列表中的每个元素上都有“间隔”单词,则需要使用split()方法来处理它。你知道吗

sentence = 'The profit in the month of November lowered from 5% to 3%.'

words = ['profit low','month high','5% 3%']

single_words = []
for w in words:
    for s in range(len(w.split(' '))):
        single_words.append(w.split(' ')[s])

matched_words = [] # Will collect the matched words in the next life loop:
[matched_words.append(word) for word in single_words if word in sentence]

print(matched_words)

相关问题 更多 >