Форум сайта python.su
Офлайн
from collections import Counter
from operator import itemgetter
from string import digits, punctuation
def frequency(infile, outfile):
vowels = "aeiouy"
c = Counter()
with open(infile, "r") as f:
for line in f:
c.update(line.strip().replace(" ", "").lower())
with open(outfile, "w") as f:
for char, freq in sorted(c.items(), key=itemgetter(1), reverse=True):
print("{}: {}".format(freq, char), file=f)
f_all = sum(y for x, y in c.items())
f_vowels = sum(y for x, y in c.items() if x in vowels)
f_digits = sum(y for x, y in c.items() if x in digits)
f_punctuation = sum(y for x, y in c.items() if x in punctuation)
return f_vowels, f_all - f_vowels - f_digits - f_punctuation, f_punctuation
Офлайн
Как немного по другому считать частоты
from collections import defaultdict
a=defaultdict(lambda :0)
for i in open("somefile", "rt").read().lower():
if i not in "\n \t"
a[i]+=1
with open("out.txt","wt") as f:
f.write(str(dict(a)))
Отредактировано (Янв. 13, 2012 19:58:27)
Офлайн