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 16进制与中文相互转换的实现方法

Python中编码问题:u'\xe6\x97\xa0\xe5\x90\x8d' 类型的转为utf-8的解决办法 相信小伙伴们遇到过类似这样的问题,python2中各种头疼的转码,类似u'...

详解利用Python scipy.signal.filtfilt() 实现信号滤波

本文将以实战的形式基于scipy模块使用Python实现简单滤波处理,包括内容有1.低通滤波,2.高通滤波,3.带通滤波,4.带阻滤波器。具体的含义大家可以查阅大学课程,信号与系统。简单...

Python3 实现串口两进程同时读写

通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出 import threading,time import serial import str...

python的debug实用工具 pdb详解

叨逼叨 首先,介绍一下 pdb 调试,pdb 是 python 的一个内置模块,用于命令行来调试 Python 代码。或许你会说,现在用 Pycharm 等编辑器来调试代码很方便,为啥要...

python pandas时序处理相关功能详解

创建时间序列 函数pd.date_range() 根据指定的范围,生成时间序列DatetimeIndex,每隔元素的类型为Timestamp。该函数应用较多。 ts = pd....