Skip to main content
 首页 » 编程设计

python之从文本文件输入中删除重复的单词

2024年11月01日10小虾米

我在玩一个函数,它有 3 个参数,一个文本文件的名称,substring1 和 substring2。它将搜索文本文件并返回包含两个子字符串的单词:

def myfunction(filename, substring1, substring2) 
    result = "" 
    text=open(filename).read().split() 
    for word in text: 
        if substring1 in word and substring2 in word: 
            result+=word+" " 
    return result 

此功能有效,但我想删除重复的结果。例如,对于我的特定文本文件,如果 substring1 是“at”而 substring2 是“wh”,它将返回“what”,但是,因为我的文本文件中有 3 个“what”,所以它会返回所有这些。我正在寻找一种不返回重复项,只返回唯一单词的方法,我也想保留 ORDER,那么这算不算“集”?

我认为也许对“文本”做一些事情会起作用,以某种方式在循环之前删除重复项。

请您参考如下方法:

这是一个使用小内存的解决方案(在文件行上使用迭代器)并且具有良好的时间复杂度(当返回的单词列表时很重要很大,比如 substring1 是“a”而 substring2 是“e”,对于英语):

import collections 
 
def find_words(file_path, substring1, substring2) 
    """Return a string with the words from the given file that contain both substrings.""" 
    matching_words = collections.OrderedDict() 
    with open(file_path) as text_file: 
        for line in text_file: 
            for word in line.split(): 
                if substring1 in word and substring2 in word: 
                    matching_words[word] = True 
    return " ".join(matching_words) 

OrderedDict 保留了键的首次使用顺序,因此这使单词按照找到它们的顺序排列。因为是映射,所以没有重复的词。由于在 OrderedDict 中插入键是在常数时间内完成的(与许多 if word in result_list 的线性时间相反,因此获得了良好的时间复杂度其他解决方案)。