0

这是我第一次在这里问问题,我对此很陌生,所以我会尽力而为。我有一个短语列表,我想消除所有类似的短语,例如:

array = ["A very long string saying some things", 
         "Another long string saying some things", 
         "extremely large string saying some things", 
         "something different", 
         "this is a test"]

我想要这个结果:

array2 = ["A very long string saying some things", 
          "something different", 
          "this is a test"]`

我有这个:

for i in range(len(array)):
    swich=True
    for j in range(len(array2)):
        if (fuzz.ratio(array[i],array2[j]) >= 80) and (swich == True):
            swich=False
            pass
        if (fuzz.ratio(array[i],array2[j]) >= 80) and (swich == False):
            array2.pop(j)

但它给了我清单IndexError......

fuzzy.ratio比较两个字符串并给出 0 到 100 之间的值,越大,字符串越相似。

我要做的是逐个元素比较列表,第一次找到两个相似的字符串时,只需打开开关并传递,从那时起,每个相似的发现,弹出array2. 我完全愿意接受任何建议。

4

2 回答 2

0

您得到的错误是由您正在迭代的列表的修改引起的。(永远不要添加/删除/替换您当前迭代的可迭代元素!)range(len(array2))知道长度是 N,但是在 you 之后array2.pop(j),长度不再是 N,而是 N-1。之后尝试访问第 N 个元素时,您会得到一个,IndexError因为列表现在更短了。

快速猜测另一种方法:

original = ["A very long string saying some things", "Another long string saying some things", "extremely large string saying some things", "something different", "this is a test"]

filtered = list()

for original_string in original:
    include = True
    for filtered_string in filtered:
        if fuzz.ratio(original_string, filtered_string) >= 80:
            include = False
            break
    if include:
        filtered.append(original_string)

请注意for string in array循环,它更“pythonic”并且不需要整数变量或范围。

于 2017-04-20T20:49:39.917 回答
0

如何使用不同的库来压缩代码并减少循环次数?

import difflib

def remove_similar_words(word_list):
    for elem in word_list:
        first_pass = difflib.get_close_matches(elem, word_list)
        if len(first_pass) > 1:
            word_list.remove(first_pass[-1])
            remove_similar_words(word_list)
    return word_list


l = ["A very long string saying some things", "Another long string saying some things", "extremely large string saying some things", "something different", "this is a test"]

remove_similar_words(l)

['A very long string saying some things',
 'something different',
 'this is a test']
于 2017-04-20T21:00:08.097 回答