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函数式编程指南(三):迭代器详解

3. 迭代器 3.1. 迭代器(Iterator)概述 迭代器是访问集合内元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素都被访问一遍后结束。 迭代器不能回退,只能往...

Tesserocr库的正确安装方式

Tesserocr库的正确安装方式

win10,直接使用 pip install tesserocr 的命令 如果输出如下错误提示: tesserocr.cpp(596): fatal error C1083: 无法打...

python 将list转成字符串,中间用符号分隔的方法

如下所示: data = [1,2,3,4] print "|".join(str(i) for i in data) 如果data中有中文: import sys reloa...

在pytorch中查看可训练参数的例子

pytorch中我们有时候可能需要设定某些变量是参与训练的,这时候就需要查看哪些是可训练参数,以确定这些设置是成功的。 pytorch中model.parameters()函数定义如下:...

Django Admin 实现外键过滤的方法

说明和 Model 环境: ➜ python Python 3.6.3 |Anaconda custom (x86_64)| (default, Oct 6 2017...