2024-05-20 01:06:42 发布
网友
我试着读一个文件中的单词,但它没有按预期工作。如果我遗漏了什么,你能告诉我吗。你知道吗
from collections import Counter wordcount=Counter(f1.read()) for k,v in wordcount.items(): print (k ,v)
文件内容包括:
DELETE INSERT DELETE INSERT UPDATE UPDATE
期待
DELETE 2 INSERT 2 ..
。。你知道吗
但它在数字母
必须使用readlines()而不是read()。此外,还需要去掉\n字符,因为使用readlines()也会读取它们。你知道吗
readlines()
read()
\n
from collections import Counter with open('chk.txt') as f: mylist = f.read().splitlines() #get rid of newline character wordcount=Counter(mylist) for k,v in wordcount.items(): print (k ,v) #Output: ('INSERT', 2) ('UPDATE', 2) ('DELETE', 2)
使用.readlines()
.readlines()
.read()连续返回char。所以计数器计算字符。 但是.readlines()返回单词(事实是一行,但在你的例子中是一行中的单词)
.read()
把你的论点改为反对。 从
wordcount=Counter(f1.read())
至
wordcount=Counter(f1.readlines().split())
必须使用
readlines()
而不是read()
。此外,还需要去掉\n
字符,因为使用readlines()
也会读取它们。你知道吗使用
.readlines()
.read()
连续返回char。所以计数器计算字符。 但是.readlines()
返回单词(事实是一行,但在你的例子中是一行中的单词)把你的论点改为反对。 从
至
相关问题 更多 >
编程相关推荐