Python编程:函数与程序开发的深度探索
1. 计算高频词的函数设计
在Python编程中,我们常常需要计算文本中高频出现的词汇。以下是一个设计良好的函数示例,用于计算给定URL文本中单词的频率分布:
def freq_words(url):
freqdist = nltk.FreqDist()
text = nltk.clean_url(url)
for word in nltk.word_tokenize(text):
freqdist.inc(word.lower())
return freqdist
我们可以使用以下代码来调用这个函数并查看结果:
>>> fd = freq_words(constitution)
>>> print fd.keys()[:20]
['the', 'of', 'charters', 'bill', 'constitution', 'rights', ',',
'declaration', 'impact', 'freedom', '-', 'making', 'independence']
实际上,我们可以将 freq_words 函数的工作简化为三行代码:
>>> words = nltk.word_tokenize(nltk.c
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



