[英]Python: how to find the closest matching sentence from a txt file
我想輸出txt文件中是否存在任何類似的句子
例:
如果.txt文件包含
1。 我們太陽系最大的星球是什么?
2。 如何泡茶?
3。 我們太陽系中哪個星球最大?
在這種情況下,它應導致:
3。 我們太陽系中哪個星球最大?
基本上,應該比較文件行中是否有超過4個或5個單詞相似
我同意約翰·科爾曼的建議。 difflib
可以幫助您找到兩個字符串之間的相似性度量。 這是一種可能的方法:
from difflib import SequenceMatcher
sentences = []
with open('./bp.txt', 'r') as f:
for line in f:
# only consider lines that have numbers at the beginning
if line.split('.')[0].isdigit():
sentences.append(line.split('\n')[0])
max_prob = 0
similar_sentence = None
length = len(sentences)
for i in range(length):
for j in range(i+1,length):
match_ratio = SequenceMatcher(None, sentences[i], sentences[j]).ratio()
if match_ratio > max_prob:
max_prob = match_ratio
similar_sentence = sentences[j]
if similar_sentence is not None:
print(similar_sentence)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.