Python程式設計入門-第11章 案例研究:文字統計
阿新 • • 發佈:2019-02-10
第11章 案例研究:文字統計
計算並列印有關文字檔案內容的統計資料:包含多少個字元、行和單詞,以及出現最多的10個單詞,並依此排列出。
#先定義一個規整文字字元的函式
def normalize(s):
keep={'a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x',
'y','z',' ','-',"'"}
result=""
for c in s.lower():
if c in keep:
result+=c
return result
#接受一個字串s並生成一個字典,該字典的鍵為s中的單詞,值為對應單詞出現的次數
def make_freq_dict(s):
s=normalize(s)
words=s.split()
d={}
for w in words:
if w in d:
d[w]+=1
else:
d[w]=1
return d
def print_file_stats(fname):
s=open(fname,'r' ).read()
#在規整字串前先統計字元數量
num_chars=len(s)
#在規整字串前先統計行數
num_lines=s.count('\n')
d=make_freq_dict(s)
#統計單詞數量
num_words=sum(d[w] for w in d)
#建立一個列表,元素為單詞及對應出現次陣列成的元組
lst=[(d[w],w) for w in d]
lst.sort()
lst.reverse()
num_words0=len(normalize(s).split())
print("The file '%s' has: " % fname)
print("%s characters"% num_chars)
print("%s lines"% num_lines)
print("%s words"% num_words)
print("%s words"% num_words0)
print("\nThe top 10 most frequent words are:")
i=1
for count,word in lst[:10]:
print("%2d. %2s %s"%(i,count,word))
i+=1
print_file_stats("3.txt")
練習:
1、修改函式printfilestats,使其也列印檔案中不同單詞總數。
#這裡只需要通過求字典長度即可得知不同單詞總數
print("There are %s different words."% len(d))
2、修改函式printfilestats,使其也列印檔案中單詞平均長度。
#計算單詞平均長度
m=0
for w in d:
m+=len(w)*d[w]
average_length=m/num_words
3、罕用語是指檔案中只出現過一次的單詞,修改函式,列印罕用語總數。
#計算罕用語數量
n=0
for w in d:
if d[w]==1:
n+=1
4、一般文章裡出現頻率較高的都是如the、a、and這些功能詞。可以建立一個排除詞集合(stop_words),可以在其中設定單詞。並在統計資料時,將該集合內的單詞排除在外。
#建立一個排除詞集合
stop_words={"the","a","i","of","is","in"}
#接受一個字串s並生成一個字典,該字典的鍵為s中的單詞,並且不在排除集合中
#值為對應單詞出現的次數
def make_freq_dict1(s):
d0=make_freq_dict(s)
d={}
for w in d0:
if w in stop_words:
continue
else:
e={w:d0[w]}
d.update(e)
return d
5、函式printfilestats將一個檔名作為輸入,並且將整個檔案讀入字串中,當檔案非常大時,會佔用大量記憶體資源。請編寫一個新的函式,逐行讀取輸入檔案。
#先定義一個規整文字字元的函式
def normalize(s):
keep={'a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x',
'y','z',' ','-',"'"}
result=""
for c in s.lower():
if c in keep:
result+=c
return result
#採用逐行讀取的方式統計
def print_file_stats(fname):
f=open(fname,'r')
#先定義並初始化統計資料
num_chars=0
num_words=0
num_lines=0
#逐行統計
for line in f:
num_chars+=len(line)
num_words+=len(normalize(line).split())
d=make_freq_dict(line,d)
num_lines+=1
print("The file '%s' has: "% fname)
print("%s characters"% num_chars)
print("%s lines"% num_lines)
print("%s words"% num_words)
print_file_stats("3.txt")