聯繫要求python
下載一首英文的歌詞或文章編碼
將歌詞存入文件中,而後讀取出來spa
將全部,.?!’:等分隔符所有替換爲空格code
將全部大寫轉換爲小寫對象
生成單詞列表blog
生成詞頻統計排序
排序ip
排除語法型詞彙,代詞、冠詞、連詞utf-8
輸出詞頻最大TOP20it
將分析對象存爲utf-8編碼的文件,經過文件讀取的方式得到詞頻分析內容。
1 io=open("test.txt",'r') 2 news=io.read() 3 io.close() 4 strList={'is','the','to','is','it','and','oh','in'} 5 for item in str1: 6 news2=news.replace(item," ").lower().split() 7 #print(news2) 8 9 wordDict={} 10 11 wordSet=set(news2) -strList 12 for w in news2: 13 wordDict[w]=news2.count(w) 14 15 16 wordList=list(wordDict.items()) 17 print(wordList) 18 for item in wordList: 19 #print(item) 20 pass 21 wordList.sort(key=lambda x:x[1],reverse=True) 22 newWordList=wordList[:20] 23 for i in newWordList: 24 print(i)
2.中文詞頻統計
下載一長篇中文文章。
從文件讀取待分析文本。
news = open('gzccnews.txt','r',encoding = 'utf-8')
安裝與使用jieba進行中文分詞。
pip install jieba
import jieba
list(jieba.lcut(news))
生成詞頻統計
排序
排除語法型詞彙,代詞、冠詞、連詞
輸出詞頻最大TOP20(或把結果存放到文件裏)
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 import jieba 4 5 str1=''''"''' 6 io=open("test2.txt",'r',encoding='UTF-8') 7 strList=io.read() 8 io.close() 9 10 print(strList) 11 wordList =list(jieba.cut(strList)) 12 for item in wordList: 13 print(item)
wordList.sort(key=lambda x:x[1],reverse=True)
newWordList=wordList[:20]
for i in newWordList:
print(i)