删除标点符号
使用正则表达式过滤掉标点符号
import refrom collections import Counter>>> text = ['this', 'is', 'a', 'sentence', '.']>>> nonPunct = re.compile('.*[A-Za-z0-9].*') # must contain a letter or digit>>> filtered = [w for w in text if nonPunct.match(w)]>>> counts = Counter(filtered)>>> countsCounter({'this': 1, 'a': 1, 'is': 1, 'sentence': 1})平均字符数
对每个单词的长度求和。除以字数。
>>> float(sum(map(len, filtered))) / len(filtered)3.75
或者,您可以利用已经进行的计数来防止重新计算。这会将单词的长度乘以我们看到它的次数,然后将所有结果相加。
>>> float(sum(len(w)*c for w,c in counts.iteritems())) / len(filtered)3.75



