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 装饰器@,对函数进行功能扩展操作。分享给大家供大家参考,具体如下: 装饰器可以对原函数进行功能扩展,但还不需要修改原函数的内容(开闭原则),也不需要修改原函数...

python调用其他文件函数或类的示例

B.py调用A.py的函数或类 在同一个文件夹下 调用函数: A.py文件: def add(x,y): print('和为:%d'%(x+y)) B.py文件: im...

python 中random模块的常用方法总结

python 中random的常用方法总结 一、random常用模块 1.random.random() 随机生成一个小数 print(random.random()) # 输出...

Python利用递归和walk()遍历目录文件的方法示例

Python利用递归和walk()遍历目录文件的方法示例

前言 经常需要检查一个“目录或文件夹”内部有没有我们想要的文件或者文件夹,就需要我们循环迭代出所有文件和子文件夹,Python中遍历指定目录下所有的文件和文件夹,包含多级目录,有两种方法...

python简单获取本机计算机名和IP地址的方法

本文实例讲述了python简单获取本机计算机名和IP地址的方法。分享给大家供大家参考。具体实现方法如下: 方法一: >>> import socket >&...