首页 > 解决方案 > 如何检查文件中是否有重复的单词

问题描述

如果文件中有任何重复项,我需要返回 True。这是我所拥有但不正确的。

def duplicate(filename):
    infile = open(filename)
    contents = infile.read()
    infile.close()
    words = contents.split()
    for word in words:
        if words.count(word) > 1:
            return True
        else:
            return False

文件内容

This is a file with a duplicate. Just one.
You may try to find another but you'll never see it.

标签: python

解决方案


您将返回第一个字数。在检查所有单词之前不要返回 false

for word in words:
    if words.count(word) > 1:
        return True
 return False

此外,你没有剥离标点符号,所以word!会是独一无二的word

Counter使用对象也更高效

另外,最好像这样打开文件

with open(filename) as infile:
    lines = infile.readlines()
    for line in lines:
        for word in line.split():
            ...
return False 

推荐阅读