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使用numpy实现BP神经网络

本文完全利用numpy实现一个简单的BP神经网络,由于是做regression而不是classification,因此在这里输出层选取的激励函数就是f(x)=x。BP神经网络的具体原理此...

Python中property属性实例解析

本文主要讲述的是对Python中property属性(特性)的理解,具体如下。 定义及作用: 在property类中,有三个成员方法和三个装饰器函数。 三个成员方法分别是:fget、f...

详细讲解Python中的文件I/O操作

详细讲解Python中的文件I/O操作

 本章将覆盖所有在Python中使用的基本I/O功能。有关更多函数,请参考标准Python文档。 打印到屏幕上: 产生输出最简单的方法是使用print语句,可以通过用逗号分隔的...

Python简单调用MySQL存储过程并获得返回值的方法

本文实例讲述了Python调用MySQL存储过程并获得返回值的方法。分享给大家供大家参考。具体实现方法如下: try: conn = MySQLdb.connect (...

在Python 中实现图片加框和加字的方法

第一步:安装opencv-python rpm -ivh opencn-python-2.4.5-3.el7.ppc64le.rpm 第二步:引用cv2 import cv2...