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列表删除元素del、pop()和remove()的区别小结

前言 在python列表的元素删除操作中, del, pop(), remove()很容易混淆, 下面对三个语句/方法作出解释 del语句 del语句可以删除任何位置处的列表元素, 若...

Python运维开发之psutil库的使用详解

介绍 psutil能够轻松实现获取系统运行的进程和系统利用率。 导入模块 import psutils 获取系统性能信息 CPU信息 使用cpu_times()方法获取CP...

讲解Python中for循环下的索引变量的作用域

我们从一个测试开始。下面这个函数的功能是什么?   def foo(lst): a = 0 for i in lst: a += i b = 1...

python pandas消除空值和空格以及 Nan数据替换方法

在人工采集数据时,经常有可能把空值和空格混在一起,一般也注意不到在本来为空的单元格里加入了空格。这就给做数据处理的人带来了麻烦,因为空值和空格都是代表的无数据,而pandas中Serie...

python中用logging实现日志滚动和过期日志删除功能

logging库提供了两个可以用于日志滚动的class(可以参考https://docs.python.org/2/library/logging.handlers.html),一个是R...