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简单商城购物车实例代码

本文为大家分享一个简单商城购物车的python代码,供大家参考,具体内容如下 要求: 1、写一段商城程购物车序的代码 2、用列表把商城的商品清单存储下来,存到列表 shopping_ma...

Python常用知识点汇总

Python常用知识点汇总

1、Set基本数据类型 a、set集合,是一个无序且不重复的元素集合 class set(object): """ set() -> new empty set ob...

python图书管理系统

本文实例为大家分享了python图书管理系统的具体代码,供大家参考,具体内容如下 实现语言:python 图形框架:DTK+2.0 数据库框架:SQLite 3.0 本程序需要以下部件运...

Sanic框架配置操作分析

本文实例讲述了Sanic框架配置操作。分享给大家供大家参考,具体如下: 简介 Sanic是一个类似Flask的Python 3.5+ Web服务器,它的写入速度非常快。除了Flask之外...

Python 使用 Pillow 模块给图片添加文字水印的方法

Python 使用 Pillow 模块给图片添加文字水印的方法

像微博一类的平台上传图片时,平台都会添加一个水印,宣誓着对图片的所有权,我们自己的博客平台也可以给自己的图片添加上水印。 还是用 Pillow 模块来实现 先来看一个简单的例子 &g...