如何计算python中文件中的字频率

The*_*oxx 2 python

我有一个.txt文件,格式如下,

C
V
EH
A
IRQ
C
C
H
IRG
V
Run Code Online (Sandbox Code Playgroud)

虽然显然它比那要大得多,但实质上就是它.基本上我试图将每个字符串在文件中的次数相加(每个字母/字符串在一个单独的行上,所以从技术上讲,文件是C \nV \nEH \n等等.但是当我尝试将这些文件转换为列表,然后使用count函数时,它会分出字母,以便'IRQ'等字符串为['\n'I','R' ,'Q','\n']所以当我算上它时,我会得到每个字母而不是字符串的频率.

这是我到目前为止编写的代码,

def countf():
    fh = open("C:/x.txt","r")
    fh2 = open("C:/y.txt","w")
    s = []
    for line in fh:
        s += line
    for x in s:
        fh2.write("{:<s} - {:<d}".format(x,s.count(x))
Run Code Online (Sandbox Code Playgroud)

我想要最终得到的是一个看起来像这样的输出文件

C  10
V  32
EH 7
A  1
IRQ  9
H 8
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 6

使用Counter(),并用于strip()删除\n:

from collections import Counter
with open('x.txt') as f1,open('y.txt','w') as f2:
    c=Counter(x.strip() for x in f1)
    for x in c:
        print x,c[x]   #do f2.write() here if you want to write them to f2
Run Code Online (Sandbox Code Playgroud)

输出:

A 1
C 3
EH 1
IRQ 1
V 2
H 1
IRG 1
Run Code Online (Sandbox Code Playgroud)