期末综合大作业:词频统计
#1, riverFile = open('river.txt','r') riverTest = riverFile.read() riverFile.close() print(riverTest) #2, print(riverTest.replace(',',' ')) print( riverTest.replace("'",' ')) print(riverTest) #3, print(riverTest.split(' ')) riverList = riverTest.split(' ') #4, riverSet = set(riverList) print( riverSet) riverDict = {} for word in riverSet: riverDict[word] = riverList.count(word) print(riverDict) for d in riverDict: print(d,riverDict [d])#5, wordCountList = list( riverDict.items()) print( wordCountList) wordCountList.sort( key=lambda x:x[1],reverse=True) print(wordCountList) #6, for i in range(20): print(wordCountList[1]) #7, riverCountFile = open('riverCou nt.txt',mode='a',encoding='utf-8') for i in range(len(wordCountList)): riverCountFile.write(str (wordCountList[i][1])+' '+wordCountList[i][0]+'\n') riverCountFile.close() 复制代码 复制代码 #1, riverFile = open('river.txt','r') riverTest = riverFile.read() riverFile.close() print(riverTest) #2, print(riverTest.replace(',',' ')) print(riverTest.replace("'",' ')) print(riverTest) #3, print(riverTest.split(' ')) riverList = riverTest.split(' ') #4, riverSet = set(riverList) print(riverSet) riverDict = {} for word in riverSet: riverDict[word] = riverList.count(word) print(riverDict) for d in riverDict: print(d,riverDict[d]) #5, wordCountList = list(riverDict.items()) print(wordCountList) wordCountList.sort(key=lambda x:x[1],reverse=True) print(wordCountList) #6, for i in range(20): print(wordCountList[1]) #7, riverCountFile = open('riverCount.txt',mode='a',encoding='utf-8') for i in range(len(wordCountList)): riverCountFile.write(str(wordCountList[i][1])+' '+wordCountList[i][0]+'\n') riverCountFile.close()