a="""winkle Twinkle Little Star - Jewel
Lyrics by Sophia Sun
Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
When the blazing sun is gone,
When he nothing shines upon,
Then you show your little light,
Twinkle, twinkle, all the night.
Then the traveller in the dark,
Thanks you for your tiny spark,
He could not see which way to go,
If you did not twinkle so.
In the dark blue sky you keep,
And often through my curtains peep,
For you never shut your eye,
Till the sun is in the sky.
As your bright and tiny spark,
Lights the traveller in the dark.
Though I know not what you are,
Twinkle, twinkle, little star.
Twinkle, twinkle, little star.
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star.
How I wonder what you are.
How I wonder what you are."""
def danci(n):
a={}
n=n.lower()
for i in n.split():
if i[-1]=="," or i[-1]==".":
j=i.replace(i[-1],"")
if j not in a:
a[j]=1
else:
a[j]+=1
else:
j=i
if j not in a:
a[j]=1
else:
a[j]+=1
c=[]
b=zip(a.keys(),a.values())
for i in b:
c.append(i)
for i in range(len(c)-1): #外層回圈三次 i分別為 0,1,2
for j in range(len(c)-i-1): # j分別為 0~2,0~1,0
if float(c[j][-1])>float(c[j+1][-1]):
c[j],c[j+1]=c[j+1],c[j]
for i in range(1,len(c)):
print(c[-i])
danci(a)
統計a字串中的單詞個數,并從單詞個數由大到小的輸出出來。
uj5u.com熱心網友回復:
生成a字典之后的代碼可以改成下面這樣,簡單點
b = sorted(a.items(),key=lambda x:x[1],reverse=True)
for i in b:
print(i)
uj5u.com熱心網友回復:
from collections import Counter
a=....
l = filter(lambda x: x != '', a.replace('\n', ' ').replace('.', '').replace(' ', ',').split(","))
print(sorted(Counter(l).items(), key = lambda item: item[1], reverse= True))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/31598.html
