简体   繁体   English

Python - 遍历字符串列表并组合部分匹配字符串

[英]Python - Iterate through a list of strings and group partial matching strings

So I have a list of strings as below: 所以我有一个字符串列表如下:

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

How do I iterate through the list and group partially matching strings without given keywords. 如何在没有给定关键字的情况下遍历列表并对部分匹配的字符串进行分组。 The result should like below: 结果如下:

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

Thank you so much. 非常感谢。

Try building an inverse index, and then you can pick whichever keywords you like. 尝试构建反向索引,然后您可以选择您喜欢的关键字。 This approach ignores word order: 这种方法忽略了词序:

index = {}
for sentence in sentence_list:
    for word in set(sentence.split()):
        index.setdefault(word, set()).add(sentence)

Or this approach, which keys the index by all possible full-word phrase prefixes: 或者这种方法,它通过所有可能的全字短语前缀来键入索引:

index = {}
for sentence in sentence_list:
    number_of_words = length(sentence.split())
    for i in xrange(1, number_of_words):
        key_phrase = sentence.rsplit(maxsplit=i)[0]
        index.setdefault(key_phrase, set()).add(sentence)

And then if you want to find all of the sentences that contain a keyword (or start with a phrase, if that's your index): 然后,如果你想找到包含关键字的所有句子(或者以短语开头,如果这是你的索引):

match_sentences = index[key_term]

Or a given set of keywords: 或者一组给定的关键字:

matching_sentences = reduce(list_of_keywords[1:], lambda x, y: x & index[y], initializer = index[list_of_keywords[0]])

Now you can generate a list grouped by pretty much any combination of terms or phrases by building a list comprehension using those indices to generate sentences. 现在,您可以通过使用这些索引构建列表推导来生成句子,从而生成按几乎任何术语或短语组合分组的列表。 Eg, if you built the phrase prefix index and want everything grouped by the first two word phrase: 例如,如果您构建了短语前缀索引并希望按前两个单词短语分组的所有内容:

return [list(index[k]) for k in index if len(k.split()) == 2]

Sequence matcher will do the task for you. 序列匹配器将为您完成任务。 Tune the score ratio for better results. 调整得分比率以获得更好的结果。

Try this: 试试这个:

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)

Output: 输出:

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

Avoid words like list in naming your variables. 在命名变量时避免使用list单词。 Also list 1 is not a valid python variable. list 1也不是有效的python变量。

Try this: 试试这个:

import sys
from itertools import groupby

#Assuming you group by the first two words in each string, e.g. 'I love', 'I hate'.

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

L = sorted(L)

result = []

for key,group in groupby(L, lambda x: x.split(' ')[0] + ' ' + x.split(' ')[1]):
    result.append(list(group))

print(result)

You can try this approach. 你可以尝试这种方法。 Although it is not the best approach, it is helpful for understanding the problem in a more methodical way. 虽然这不是最好的方法,但有助于以更有条理的方式理解问题。

from itertools import groupby

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

each_word = sorted([x.split() for x in my_list])

# I assumed the keywords would be everything except the last word
grouped = [list(value) for key, value in groupby(each_word, lambda x: x[:-1])]

result = []
for group in grouped:
    temp = []
    for i in range(len(group)):
        temp.append(" ".join(group[i]))
    result.append(temp)

print(result)

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM