Python 获取文件中的字数

Python get count of words in a file

我正在尝试读取文件中的文字,但它似乎无法正常工作。如果我遗漏了什么,你能告诉我吗?

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() return 连续字符。所以 Counter 对 char 进行计数。 but .readlines() return word(事实是一行,但在你的情况下,一行中的一个词)

Use readlines() instead of read,

from collections import Counter

f1 = open("test.txt", "r")
wordcount=Counter(f1.readlines())

#print(wordcount)

for k,v in wordcount.items():
    print (k ,v)

要获得更好的结果,请使用 split() 或 splitlines() 删除 \n

wordcount=Counter(f1.readlines().splitlines())
# or
wordcount=Counter(f1.read().split())

输出:

DELETE 2
INSERT 2
UPDATE 2

您必须使用 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)

只需更改您对 Counter 的论点。 来自

wordcount=Counter(f1.read())

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