【Python】实现文章字符频次排序(文件IO、列表排序、字典操作和字符串join方法)

实现文章频次排序:

fi = open("小女孩-频次排序.txt","w")
fo = open("小女孩.txt","r")
d = {}
txt = fo.read()
exclude = ", 。 —— !? “ ” :"#需要屏蔽的标点符号
for s in txt:
    if s in exclude:
        continue
    else:
        d[s] = d.get(s,0)+1
del d["\n"]
ls = list(d.items())
ls.sort(key=lambda x:x[1], reverse=True) # 此行可以按照词频由高到低排序
for i in range(len(ls)):
    ls[i] = "{}:{}".format(ls[i][0],ls[i][1])#重新编排列表格式
fi.write(",".join(ls))
fo.close()
fi.close()

Tips:要实现指定格式的字符输出的时候可以重新编排列表格式后输出

发布了88 篇原创文章 · 获赞 39 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43444989/article/details/100555721