pyhton学习之找出单词的个数并进行排序

在学习C的时候,我们经常会做这样的算法题来提高我们的编程能力,然而在python中使用封装好的类库,就可以简单完成。

需要的模块有:re :该模块可以通过一定的规则寻找目标   Counter主要是用于统计个数

代码:

#coding:utf-8


import re
from collections import Counter


filePath = './sound.txt'


def getCountWords(file):
"统计输入文件内容中单词的个数"
pattern = "[A-Za-z]+|\$?\d+%?$"
with open(file) as f:
r = re.findall(pattern,f.read())
print r
print '*'*20
return Counter(r).most_common()


if __name__ == '__main__':

print getCountWords(filePath)


sound.txt中的内容为:

  When I was young I'd listen to the radio 
  Waiting for my favorite songs 
  When they played I'd sing along, 
  It make me smile. 
  Those were such happy times and not so long ago 
  How I wondered where they'd gone. 
  But they're back again just like a long lost friend 
  All the songs I love so well. 
  Every shalala every wo'wo 
  still shines. 
  Every shing-a-ling-a-ling that they're starting to sing 
  so fine 
  When they get to the part 
  where he's breaking her heart 
  It can really make me cry 
  just like before. 
  It's yesterday once more. 
  (Shoobie do lang lang) 
  Looking bak on how it was in years gone by 
  And the good times that had 
  makes today seem rather sad, 
  So much has changed. 
  It was songs of love that I would sing to them 
  And I'd memorise each word. 
  Those old melodies still sound so good to me 
  As they melt the years away 
  Every shalala every wo'wo still shines 
  Every shing-a-ling-a-ling that they're startingTo sing 
  so fine 
  All my best memorise come back clearly to me 
  Some can even make me cry 
  just like before. 
  It's yesterday once more. 
  (Shoobie do lang lang) 
  Every shalala every wo'wo still shines. 
  Every shing-a-ling-a-ling that they're starting to sing 
  so fine 
  Every shalala every wo'wo still shines. 
  Every shing-a-ling-a-ling that they're starting to sing 
  so fine 
  昨日重现 (中文歌词) 歌手:卡朋特 
  年少时我喜欢听着收音机 等候我喜欢的歌曲轻轻响起 
  我独自为它伴唱 让我感到欢喜 这样的幸福时光早已远去 
  我多想知道他们到了那里? 象失散朋友再次回来 所有的歌曲 
  我还是那样喜欢 每一句 sha la la la 每一句wo wo 仍散发光芒 
  每一句sing aling aling 他们唱得还是如此动听 
  当歌曲演绎到 伤心的地方 确实让我哭泣 这是 昨日重现啊 
  回头看看走过的这些时光 幸福记忆让今天的我很感伤 有太多已经改变 
  那首我曾为他唱的爱情歌曲 每句歌词还印在我脑海里 
  那些旧的记忆依旧那么美妙 为我带走 这么多年的忧伤 
  每一句 sha la la la 每一句wo wo 仍散发光芒 
  每一句sing aling aling 他们唱得还是如此动听 所有美妙回忆 

  清晰向我袭击 一些确实让我哭泣 就象以前那样 这是昨日重现啊

结果为:


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页