python - 如何检查文件中是否有重复的单词
问题描述
如果文件中有任何重复项,我需要返回 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.
解决方案
您将返回第一个字数。在检查所有单词之前不要返回 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
推荐阅读
- macos - 使用图像创建 CISampler 时如何设置 kCISamplerAffineMatrix
- google-cloud-platform - gcloud dataproc clusters update - 如何删除阻止命令成功运行的挂起更新
- apache-spark - 为什么我们需要虚拟机来安装和使用 Apache Spark?
- c - 从 C 中按值传递的结构打印
- excel - 将 PtrSafe 添加到 vba 函数调用到第 3 方 dll 会导致 64 位 Excel 中的错误
- python - 使用 youtube_dl 通过 if 和 elif 语句下载 youtube 视频
- string - 为什么 bash 不让我编辑这个字符串?
- javascript - 为什么 Map() === Map() 评估为真?
- python - Python CSV 数据到 XML
- mysql - 您将如何“规范化”此 SQL?