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

yipeiwu_com5年前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使用matplotlib绘制随机漫步图

Python使用matplotlib绘制随机漫步图

本文我们来做一个简单的随机漫步数据图,进一步了解matplotlib的使用, 使用Python生成随机漫步数据,再使用matplotlib绘制出来, 随机漫步是这样行走得到的路径: 每次...

Python MySQLdb Linux下安装笔记

在家里windows环境下搞了一次 见   python MySQLdb在windows环境下的快速安装、问题解决方式 /post/65746.htm 在公司开发需要...

python无限生成不重复(字母,数字,字符)组合的方法

使用python自带的itertools模块 调用其product函数 传入我们想组合生成的字符数据 便会源源不断的生成组合 而且不会重复 repeat参数指定生成多少位 impor...

python str与repr的区别

尽管str(),repr()和``运算在特性和功能方面都非常相似,事实上repr()和``做的是完全一样的事情,它们返回的是一个对象的“官方”字符串表示,也就是说绝大多数情况下可以通过求...

Python之PyUnit单元测试实例

本文实例讲述了Python之PyUnit单元测试,与erlang eunit单元测试很像,分享给大家供大家参考。具体方法如下: 1.widget.py文件如下: 复制代码 代码如下:#!...