How to count word frequencies within a file in python

use Counter(), and use strip() to remove the \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

output:

A 1
C 3
EH 1
IRQ 1
V 2
H 1
IRG 1

Leave a Comment