时间:2021-05-22
本文实例讲述了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 str1print# create a list of words separated at whitespaceswordList1 = str1.split(None)# strip any punctuation marks and build modified word list# start with an empty listwordList2 = []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 wordList2print# create a wordfrequency dictionary# start with an empty dictionaryfreqD2 = {}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 alreadykeyList = 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程序设计有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了Python实现简单文本字符串处理的方法。分享给大家供大家参考,具体如下:对于一个文本字符串,可以使用Python的string.split()方
本文实例讲述了python统计字符串中指定字符出现次数的方法。分享给大家供大家参考。具体如下:python统计字符串中指定字符出现的次数,例如想统计字符串中空格
定义字符串(String)对象JavaScriptString对象用于处理文本字符串。创建String对象语法如下:复制代码代码如下:varstr_object
python中count函数的用法count()函数描述:统计字符串里某个字符出现的次数,可以选择字符串索引的起始位置和结束位置。语法:str.count("c
1、JS字符串的替换及replace()方法的使用replace(regexp,replacement)方法有两个参数,第一参数可以是一个纯文本字符串或是一个R