Python學習--統計字串中單詞的數目
阿新 • • 發佈:2019-02-04
Python在這些年異常的火爆,這也得益於其功能的龐大效率的高效以及第三方庫的。最近也來追一下“潮流”哈。
統計單詞出現的次數可以做搜尋,也可做關聯。Python實現起來也非常方便。(只支援英文)
具體程式碼如下:
from collections import Counter import re cnt=Counter(); f=open("mytest.txt"); for w in f : print(w); w = w.lower(); # 正則表示式替換特殊字元 #w = w.replace("\n",""); w=re.sub("[!,\n,!]","" ,w); for word in w.split(" "): cnt[word] += 1; print(cnt)
利用到了正則和集合兩個類。
其中正則是為了去掉字串中的標點符號。(也可以用replace實現或者translate)
使用規則如下:
# translate把其轉換成字串
s = 'abc123xyz'
print(s.translate(str.maketrans('abcxyz', 'xyzabc')))
結果:xyz123abc