1. 程式人生 > >python讀取檔案裡的單詞,統計詞頻,輸出到檔案

python讀取檔案裡的單詞,統計詞頻,輸出到檔案

(2017-05-15 優化的程式碼)

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
'''
程式用python3執行時,可將當前路徑下的aa.txt檔案讀取後,按空格分割成一系列的單詞,
然後統計這些單詞出現的次數,按頻率從大到小排序後,寫入ar.txt檔案中。
涉及的語法有:
1、中英文混合對齊;
2、collections.Counter;
3、獲取當前路徑、檔案讀寫、路徑與檔名組合、隨機數生成。。。
'''
import os
from random import choice, randint
from collections import Counter
from
string import ascii_letters as letters #假設要讀取檔名為aa,位於當前路徑 filename = 'aa.txt' dirname = os.getcwd() fname = os.path.join(dirname, filename) #註釋掉的程式段,用於測試指令碼,它生成20行資料,每行有1-20隨機個數字,每個數字隨機1-20 #''' lines = [] for i in range(20): line = [] for j in range(randint(1,20)): line.append(''.join([choice(letters) for
c in range(randint(1, 10))])) lines.append(' '.join(line)) with open(fname, 'w') as f: f.write('\n'.join(lines)) #''' with open(fname) as f: s = f.read() counter = Counter(s.replace('\n', ' ').split(' ')) # 格式化要輸出的每行資料,首尾各佔8位,中間佔18位 def geshi(a,b,c): return alignment(str(a))+alignment(str(b),18
)+alignment(str(c))+'\n' # 中英文混合對齊 ,參考http://bbs.fishc.com/thread-67465-1-1.html ,二樓 # 漢字與字母 格式化佔位 format對齊出錯 對不齊 漢字對齊數字 漢字對齊字母 中文對齊英文 # alignment函式用於英漢混合對齊、漢字英文對齊、漢英對齊、中英對齊 def alignment(str1, space=8, align = 'left'): length = len(str1.encode('gbk')) space = space - length if space >=length else 0 if align in ['left','l','L','Left','LEFT']: return str1 + ' ' * space elif align in ['right','r','R','Right','RIGHT']: return ' '* space + str1 elif align in ['center','c','C','Center','CENTER','centre']: return ' ' * (space // 2) + str1 + ' ' * (space - space // 2) return 'Unknow align format' title = geshi('序號', '詞', '頻率') results = [] #要輸出的資料,每一行由:序號(佔8位)詞(佔20位)頻率(佔8位)+'\n'構成,序號=List.index(element)+1 for i, (w, c) in enumerate(counter.most_common(), 1): results.append(geshi(i,w,c)) #將統計結果寫入檔案ar.txt中 writefile = 'ar.txt' wpath = os.path.join(dirname, writefile) with open(wpath, 'w') as f: f.write(''.join([title]+results))

(2016-11-03 寫的程式碼)

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
'''
程式用python3執行時,可將當前路徑下的aa.txt檔案讀取後,按空格分割成一系列的單詞,
然後統計這些單詞出現的次數,按頻率從大到小排序後,寫入ar.txt檔案中。
涉及的語法有:
1、中英文混合對齊;
2、list高階排序,一組升,一組降;
3、獲取當前路徑、檔案讀寫、路徑與檔名組合、隨機數生成。。。
'''
import os,random

#假設要讀取檔名為aa,位於當前路徑
filename='aa.txt'
dirname=os.getcwd()
f_n=os.path.join(dirname,filename)

#註釋掉的程式段,用於測試指令碼,它生成20行資料,每行有1-20隨機個數字,每個數字隨機1-20
'''
test=''
for i in range(20): 
    for j in range(random.randint(1,20)): 
        test+=str(random.randint(1,20))+' ' 
        test+='\n'
with open(f_n,'w') as wf:
    wf.write(test)
'''
with open(f_n) as f: 
    s=f.readlines()

# 將每一行資料去掉首尾的空格和換行符,然後用空格分割,再組成一維列表
words=[]
for line in s: 
    words.extend(line.strip().split(' '))   

# 格式化要輸出的每行資料,首尾各佔8位,中間佔18位
def geshi(a,b,c): 
    return alignment(str(a))+alignment(str(b),18)+alignment(str(c))+'\n'    

# 中英文混合對齊 ,參考http://bbs.fishc.com/thread-67465-1-1.html ,二樓
# 漢字與字母 格式化佔位 format對齊出錯 對不齊 漢字對齊數字 漢字對齊字母 中文對齊英文
# alignment函式用於英漢混合對齊、漢字英文對齊、漢英對齊、中英對齊
def alignment(str1, space=8, align = 'left'): 
    length = len(str1.encode('gb2312')) 
    space = space - length if space >=length else 0 
    if align in ['left','l','L','Left','LEFT']: 
        str1 = str1 + ' ' * space 
    elif align in ['right','r','R','Right','RIGHT']: 
        str1 = ' '* space +str1 
    elif align in ['center','c','C','Center','CENTER','centre']: 
        str1 = ' ' * (space //2) +str1 + ' '* (space - space // 2) 
    return str1

w_s=geshi('序號','詞','頻率')

#由(詞,頻率)元組構成列表,先按頻率降序排序,再按詞升序排序,多級排序,一組升,一組降,高階sorted
wordcount=sorted([(w,words.count(w)) for w in set(words)],key=lambda l:(-l[1],l[0]))

#要輸出的資料,每一行由:序號(佔8位)詞(佔20位)頻率(佔8位)+'\n'構成,序號=List.index(element)+1
for (w,c) in wordcount: 
    w_s+=geshi(wordcount.index((w,c))+1,w,c)    

#將統計結果寫入檔案ar.txt中
writefile='ar.txt'
w_n=os.path.join(dirname,writefile)
with open(w_n,'w') as wf: 
    wf.write(w_s)