词频统计

#1.
salahFile = open('salah.txt',mode="r",encoding='utf-8')
salahText = salahFile.read()
salahFile.close()
print(salahText)

#2.
replaceList = [',','.',"'",'\n']
for c in replaceList:
salahText =salahText.replace(c,' ')
print(salahText)

#3.
print(salahText.split(' '))
salahList = salahText.split(' ')

#4.
salahSet = set(salahList)
print(salahSet)

salahDict = {}
for word in salahSet:
salahDict[word] = salahList.count(word)

print(salahDict)
for d in salahDict:
print(d,salahDict[d])

#5.
wordCountList = list(salahDict.items())
print(wordCountList)
wordCountList.sort(key=lambda x:x[1],reverse=True)
print(wordCountList)

#6.
for i in range(20):
print(wordCountList)

#7.
salahCountFile = open('salahCount.txt',mode='a',encoding='utf-8')
for i in range(len(wordCountList)):
salahCountFile.write(str(wordCountList[i][1])+' '+wordCountList[i][0]+'\n')
salahCountFile.close()
posted @ 2018-06-20 21:13  李凌正  阅读(87)  评论(0编辑  收藏  举报