给定一个可迭代sequence,对其中的值进行出现次数统计:
方法1:
def get_counts(sequence):
counts = {}
for x in sequence:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
return counts
方法2:
利用python中内置的collections
from collections import defaultdict
def get_coun
本文实例讲述了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 "Origin
问题描述:
用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单词。返回值是一个元组列表,包含出现次数最高的 n 个单词及其次数,即 [(, ), (, ), … ],按出现次数降序排列。
您可以假设所有输入都是小写形式,并且不含标点符号或其他字符(只包含字母和单个空格)。如果出现次数相同,则按字母顺序排列。
例如:
print count_words("betty bought a bit of butter but
本文实例讲述了PHP编程计算文件或数组中单词出现频率的方法。分享给大家供大家参考,具体如下:
如果是小文件,可以一次性读入到数组中,使用方便的数组计数函数进行词频统计(假设文件中内容都是空格隔开的单词):
<?php
$str = file_get_contents("/path/to/file.txt"); //get string from file
preg_match_all("/\b(\w+[-]\w+)|(\w+)\b/",$str,$r); //place words in