Python获取fi中的字数

2024-05-20 01:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着读一个文件中的单词,但它没有按预期工作。如果我遗漏了什么,你能告诉我吗。你知道吗

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 ..

。。你知道吗

但它在数字母


Tags: 文件infromimportforreadcounterupdate
3条回答

必须使用readlines()而不是read()。此外,还需要去掉\n字符,因为使用readlines()也会读取它们。你知道吗

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()

.read()连续返回char。所以计数器计算字符。 但是.readlines()返回单词(事实是一行,但在你的例子中是一行中的单词)

把你的论点改为反对。 从

wordcount=Counter(f1.read())

wordcount=Counter(f1.readlines().split())

相关问题 更多 >