Python統計字符出現次數(Counter包)以及txt文件寫入


# -*- coding: utf-8 -*-
#spyder (python 3.7)

1. 統計字符(可以在jieba分詞之后使用)

from collections import Counter
from operator import itemgetter

# txt_list可以寫成函數參數進行導入
txt_list = ['千古','人間','人間','','','','哈哈哈','人才','千古','千古']
c = Counter()
for x in txt_list:
    if len(x) >= 1:
        if x == '\r\n' or x == '\n' or x == ' ':
            continue
        else:
            c[x] += 1
print('常用詞頻統計結果: \n')
for (k, v) in c.most_common(4): #打印排名前四位
    print('%s%s %s  %d' % ('  ' * (3 ), k, '*' * 3, v))

# 按照詞頻數從大到小打印
d = sorted(c.items(),key=itemgetter(1),reverse = True)
for ss,tt in d:
    out_words=ss + '\t' + str(tt)
    print(out_words)

2. 多次覆蓋,循環寫入文件

#寫入文件,多次寫入,后一次覆蓋前一次,但是out_words本身是在疊加的
#即:第一次寫入的是:千古\t3\n;第二次寫入的是:千古\t3\n龍\t3\n,覆蓋上一次的數據;
#第三次是:千古\t3\n龍\t3\n人間\t2\n,繼續覆蓋上一次的數據
out_words = ''
for ss,tt in d:
    out_words=out_words + ss + '\t' + str(tt) + '\n'
    with open(r".\sss.txt", "w",encoding='utf-8') as f:
        f.write(out_words+'\n')

比如,循環兩次的結果是:

 3. 一次性寫入文件,中間不會覆蓋和多次寫入;但是如果重復運行代碼,則會覆蓋之前的全部內容,一次性重新寫入所有新內容

out_words = ''
for ss,tt in d:
    out_words=out_words + ss + '\t' + str(tt) + '\n'
with open(r".\ttt.txt", "w",encoding='utf-8') as f:
        f.write(out_words+'\n')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM