python统计文本字符串里单词出现频率的方法

yipeiwu_com6年前Python基础

本文实例讲述了python统计文本字符串里单词出现频率的方法。分享给大家供大家参考。具体实现方法如下:

# word frequency in a text
# tested with Python24  vegaseat  25aug2005
# Chinese wisdom ...
str1 = """Man who run in front of car, get tired.
Man who run behind car, get exhausted."""
print "Original string:"
print str1
print
# create a list of words separated at whitespaces
wordList1 = str1.split(None)
# strip any punctuation marks and build modified word list
# start with an empty list
wordList2 = []
for word1 in wordList1:
  # last character of each word
  lastchar = word1[-1:]
  # use a list of punctuation marks
  if lastchar in [",", ".", "!", "?", ";"]:
    word2 = word1.rstrip(lastchar)
  else:
    word2 = word1
  # build a wordList of lower case modified words
  wordList2.append(word2.lower())
print "Word list created from modified string:"
print wordList2
print
# create a wordfrequency dictionary
# start with an empty dictionary
freqD2 = {}
for word2 in wordList2:
  freqD2[word2] = freqD2.get(word2, 0) + 1
# create a list of keys and sort the list
# all words are lower case already
keyList = freqD2.keys()
keyList.sort()
print "Frequency of each word in the word list (sorted):"
for key2 in keyList:
 print "%-10s %d" % (key2, freqD2[key2])

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python 字典 按key值大小 倒序取值的实例

如下所示: viedoUrl_dict = {1:'hello',2:'python',3:'nihao'} bit_list = sorted(viedoUrl_dict.keys...

Python中非常实用的一些功能和函数分享

在使用Python多年以后,我偶然发现了一些我们过去不知道的功能和特性。一些可以说是非常有用,但却没有充分利用。考虑到这一点,我编辑了一些你应该了解的Python功能特色。 带任意数量参...

wxPython实现分隔窗口

wxPython实现分隔窗口

本文实例为大家分享了wxPython分隔窗口的具体代码,供大家参考,具体内容如下 1、分割窗口 分隔窗口(wx.SplitterWindow)就是将窗口分成两部分,即左右或上下两部分,如...

Python实现数据结构线性链表(单链表)算法示例

Python实现数据结构线性链表(单链表)算法示例

本文实例讲述了Python实现数据结构线性链表(单链表)算法。分享给大家供大家参考,具体如下: 初学python,拿数据结构中的线性链表存储结构练练手,理论比较简单,直接上代码。 #...

pycharm执行python时,填写参数的方法

pycharm执行python时,填写参数的方法

1、按快捷键:alt+shift+F10调出运行窗口,之后选择Edit Configurations或者按0 2、输入参数,点击运行 以上这篇pycharm执行python时,填写参...