python实现读取文件英文词频统计并写入到文件

# _*_ coding: utf-8 _*_
# 作者:dcjmessi

import os
from collections import Counter

# 假设要读取文件名为read,位于当前路径
filename = 'read.txt'
# 当前进程工作目录
dirname = os.getcwd()
fname = os.path.join(dirname, filename)

with open(fname) as f:
    s = f.read()

counter = Counter(s.replace('\n', ' ').split(' '))

# 格式化要输出的每行数据,尾占8位,首占18位
def geshi(a, b):
    return "{:<18}""{:>8}".format(a,b) + '\n'

title = geshi('词', '频率')
results = []
# 要输出的数据,每一行由:词、频率+'\n'构成,序号=List.index(element)+1
for w, c in counter.most_common():
    results.append(geshi(w, c))

# 将统计结果写入文件write.txt中
writefile = 'write.txt'
wpath = os.path.join(dirname, writefile)
with open(wpath, 'w') as f:
    f.write(''.join([title] + sorted(results)))

不足之处:写入到文件不能列对齐。。。。
本篇参考:https://blog.csdn.net/jaket5219999/article/details/53022735?fps=1&locationNum=10

你可能感兴趣的:(python)