NLTK书中有几个单词计数的例子,但实际上它们不是字数而是令牌数.例如,第1章,计数词汇表说以下给出了一个单词计数:
text = nltk.Text(tokens)
len(text)
Run Code Online (Sandbox Code Playgroud)
但是,它没有 - 它给出了一个单词和标点符号.你怎么能得到真实的字数(忽略标点符号)?
同样,如何获得单词中的平均字符数?显而易见的答案是:
word_average_length =(len(string_of_text)/len(text))
Run Code Online (Sandbox Code Playgroud)
然而,这将是关闭因为:
我在这里错过了什么吗?这必须是一个非常常见的NLP任务......
pet*_*tra 14
使用nltk进行标记
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
text = "This is my text. It icludes commas, question marks? and other stuff. Also U.S.."
tokens = tokenizer.tokenize(text)
Run Code Online (Sandbox Code Playgroud)
返回
['This', 'is', 'my', 'text', 'It', 'icludes', 'commas', 'question', 'marks', 'and', 'other', 'stuff', 'Also', 'U', 'S']
Run Code Online (Sandbox Code Playgroud)
dhg*_*dhg 10
使用正则表达式过滤掉标点符号
import re
from 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)
>>> counts
Counter({'this': 1, 'a': 1, 'is': 1, 'sentence': 1})
Run Code Online (Sandbox Code Playgroud)
求和每个单词的长度.除以单词数.
>>> float(sum(map(len, filtered))) / len(filtered)
3.75
Run Code Online (Sandbox Code Playgroud)
或者你可以利用你已经做过的计数来阻止一些重新计算.这会将单词的长度乘以我们看到它的次数,然后将所有这些加起来.
>>> float(sum(len(w)*c for w,c in counts.iteritems())) / len(filtered)
3.75
Run Code Online (Sandbox Code Playgroud)