【发布时间】:2018-11-12 20:42:07
【问题描述】:
在我的作业中,我有一个文本,我想计算该词在文本中出现的次数。例如,假设我有一个文本文件说。
我有很多猫和狗。我有 3 只猫和 16 只狗。我喜欢狗!
因为狗这个词出现了 3 次,所以我需要输出是那个数字。但是,我将如何为随机文本执行此操作?
到目前为止,我想出了以下内容。
file = open('phrases.txt')
text = file.read()
file.close()
count = countWords()
duplicates = 0
for words in text:
if words #appear twice or more
#if duplicates
duplicates+=1
unique = count - duplicates
#subtract the total, by the amount of duplicates.
print(unique)
countWords() 是我制作的另一个函数,它计算文本中的总单词量**
【问题讨论】:
-
字典`? collections.Counter?
-
欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topic、how to ask 和 ... the perfect question 在此处申请。特别是 5N,我们希望您在此处发布之前研究您的问题。
标签: python string python-3.x list file-io