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操作摄像头截图实现远程监控的例子

最近用python写了一个远程监控的程序,主要功能有:1.用邮件控制所以功能2.可以对屏幕截图,屏幕截图发送到邮箱3.可以用摄像头获取图片,这些图片上传到七牛4.开机自启动 复制代码 代...

浅析Python与Mongodb数据库之间的操作方法

MongoDB 是目前最流行的 NoSQL 数据库之一,使用的数据类型 BSON(类似 JSON)。 1. 安装Mongodb和pymongo Mongodb的安装和配置 Mongodb...

Python lambda表达式用法实例分析

本文实例讲述了Python lambda表达式用法。分享给大家供大家参考,具体如下: lambda表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数...

详解python中递归函数

函数执行流程 def foo1(b,b1=3): print("foo1 called",b,b1) def foo2(c): foo3(c) print...

Flask框架中request、请求钩子、上下文用法分析

本文实例讲述了Flask框架中request、请求钩子、上下文用法。分享给大家供大家参考,具体如下: request 就是flask中代表当前请求的request对象: 常用的属性如下:...