gpt4 book ai didi

Python - 迭代字符串列表并对部分匹配的字符串进行分组

转载 作者:行者123 更新时间:2023-12-02 23:53:07 25 4
gpt4 key购买 nike

所以我有一个字符串列表,如下所示:

list = ["I love cat", "I love dog", "I love fish", "I hate banana", "I hate apple", "I hate orange"]

如何在没有给定关键字的情况下迭代列表并对部分匹配的字符串进行分组。结果应如下所示:

list 1 = [["I love cat","I love dog","I love fish"],["I hate banana","I hate apple","I hate orange"]]

非常感谢。

最佳答案

序列匹配器将为您完成任务。调整分数比率以获得更好的结果。

试试这个:

from difflib import SequenceMatcher
sentence_list = ["I love cat", "I love dog", "I love fish", "I hate banana", "I hate apple", "I hate orange"]
result=[]
for sentence in sentence_list:
if(len(result)==0):
result.append([sentence])
else:
for i in range(0,len(result)):
score=SequenceMatcher(None,sentence,result[i][0]).ratio()
if(score<0.5):
if(i==len(result)-1):
result.append([sentence])
else:
if(score != 1):
result[i].append(sentence)

输出:

[['I love cat', 'I love dog', 'I love fish'], ['I hate banana', 'I hate apple', 'I hate orange']]

关于Python - 迭代字符串列表并对部分匹配的字符串进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com