期末综合大作业:词频统计

f = open('Farmer.txt',mode='r',encoding='utf-8')
fText = f.read()
f.close()

replacelist = ['.', ',', "'", '"', '?','\n','\ufeffChapter']
for c in replacelist:
    fText = fText.replace(c,' ')
print(fText)

fList = fText.split(' ')
print(fText.split(' '))

fSet = set(fList)
print(fSet)

fDict = {}
for word in fSet:
    fDict[word] = fList.count(word)
print(fDict)
for d in fDict:
    print(d,fDict[d])

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

for i in range(20):
    print(wordCountList[i])

fCountFile =open('F.txt',mode='a',encoding='utf-8')
for i in range(len(wordCountList)):
    fCountFile.write(str(wordCountList[i][1])+' '+wordCountList[i][0]+'\n')
fCountFile.close()

期末综合大作业:词频统计_第1张图片期末综合大作业:词频统计_第2张图片期末综合大作业:词频统计_第3张图片期末综合大作业:词频统计_第4张图片

你可能感兴趣的:(期末综合大作业:词频统计)