[英]counting the unique words in a text file
文本文件中的一些独特的词不算数,我不知道我的代码有什么问题。
file = open('tweets2.txt','r')
unique_count = 0
lines = file.readlines()
line = lines[3]
per_word = line.split()
for i in per_word:
if line.count(i) == 1:
unique_count=unique_count + 1
print(unique_count)
file.close()
这是文本文件:“我喜欢 REDACTED 和 Fiesta,除了 strand days 之外,REDACTED 还能举办更多与学术相关的活动吗???”
这段代码的output是:16
来自文本文件的代码的预期 output 应该是:17
“如果 REDACTED 将复课时间推迟到 1 月 7 日,我会在头上敲一个生鸡蛋。我不是在开玩笑。”
这段代码的output是:20
来自文本文件的代码的预期 output 应该是:23
如果要计算整个文件中唯一的空格分隔标记(区分大小写)的数量,则:
with open('myfile.txt') as infile:
print(len(set(infile.read().split())))
也许 count() 适用于字符而不是单词,而是使用 python 方法和 set() function 来清除重复的单词?
per_word = set(line.split())
print (len(per_word))
您将整行中的每个单词都计为 substring,因为您这样做:
for i in per_word:
if line.count(i) == 1:
所以现在有些单词作为子字符串重复,而不是作为单词重复。 例如,第一个词是"i"
。 line.count("i")
给出 7(它也在"if"
、 "im"
等中)所以你不要把它算作一个唯一的词(即使它是)。 如果你这样做:
for i in per_word:
if per_word.count(i) == 1:
然后你会把每个单词算作一个完整的单词,得到你需要的output。
无论如何,这是非常低效的( O(n^2)
),因为您遍历每个单词然后再次对整个列表进行count
以对其进行计数。 按照其他答案中的建议使用set
或使用Counter
:
from collections import Counter
unique_count = 0
line = "i will crack a raw egg on my head if REDACTED move the resumption of classes to Jan 7. im not even kidding."
per_word = line.split()
counter = Counter(per_word)
for count in counter.values():
if count == 1:
unique_count += 1
# Or simply
unique_count = sum(count == 1 for count in counter.values())
print(unique_count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.