str2='''I will run, I will climb, I will soarI'm undefeatedJumpiing out of my skin, pull the chordYeah I believe itThe past, is everything we weredon't make us who we areSo I'll dream, until I make it real,and all I see is starsIts not until you fall that you flyWhen your dreams come alive you're unstoppableTake a shot, chase the sun, find the beautifulWe will glow in the dark turning dust to goldAnd we'll dream it possiblepossibleAnd we'll dream it possibleI will chase, I will reach, I will flyUntil I'm breaking, until I'm breakingOut of my cage, like a bird in the nightI know I'm changing, I know I'm changingIn, into something big, better than beforeAnd if it takes, takes a thousand livesThen it's worth fighting forIts not until you fall that you flyWhen your dreams come alive you're unstoppableTake a shot, chase the sun, find the beautifulWe will glow in the dark turning dust to goldAnd we'll dream it possibleit possibleFrom the bottom to the topWe're sparking wild fire'sNever quit and never stopThe rest of our livesFrom the bottom to the topWe're sparking wild fire'sNever quit and never stopIts not until you fall that you flyWhen your dreams come alive you're unstoppableTake a shot, chase the sun, find the beautifulWe will glow in the dark turning dust to goldAnd we'll dream it possiblepossibleAnd we'll dream it possible'''.lower()#aa = '''."?!'''#for word in aa:# str2 =str2.replace('word','')str2 =str2.replace('\n',' ')str2 =str2.replace(',',' ')print(str2)#去除特殊符号 str2 = str2.strip()#去掉首尾空格str2 = str2.split()#通过指定分隔符对字符串进行切片print(str2) print('统计每个单词出现的次数为:')for word in str2: print(word,str2.count(word)) strSet=set(str2)newSet={'a','will','it','out','of','my','the','i','in','to','when','and'}strSet1=strSet-newSet#去除介词和其他print(strSet1) strdict={} #单词计数字典for word in strSet1: strdict[word] = str2.count(word)print(len(strdict),strdict) strList = list(strdict.items())def takesecond(elem):#定义函数 return elem[1]#strList.sort(key=lambda x:x[1],reverse=True)#匿名函数strList.sort(key=takesecond,reverse=True)#按照数值大小进行排序print(strList) for i in range(20): print (strList[i])#前二十
import jiebaf=open('《活着》.txt','r',encoding='utf-8')life=f.read()f.close()lifelist=list(jieba.cut(life))lifedict={}for word in lifelist: if len(word)==1: continue else: lifedict[word]=lifedict.get(word,0)+1 wordlist=list(lifedict.items())wordlist.sort(key=lambda x:x[1],reverse=True) for a in range(15): print(wordlist[a])