6.7 综合项目

    为了深入理解列表的使用方法,在本章的最后,我们来做一个词频统计。需要瓦尔登湖的文本,可以在这里下载:http://pan.baidu.com/s/1o75GKZ4,下载后用 PyCharm 打开文本重新保存一次,这是为了避免编码的问题。

    之前还是提前做一些准备,学习一些必要的知识。

    lyric = 'The night begin to shine, the night begin to shine'
    words = lyric.split()

    现在我们使用 split 方法将字符串中的每个单词分开,得到独立的单词:

    ['The', 'night', 'begin', 'to', 'shine']

    接下来是词频统计,我们使用 count 方法来统计重复出现的单词:

    path = '/Users/Hou/Desktop/Walden.txt'
    with open(path,'r') as text:
    words = text.read().split()
    print(words)
    for word in words:
    print('{}-{} times'.format(word,words.count(word)))

    结果出来了,但是总感觉有一些奇怪,仔细观察得出结论:

    • 有一些带标点符号的单词被单独统计了次数;
    • 有些单词不止一次地展示了出现的次数;
    • 由于 Python 对大小写敏感,开头大写的单词被单独统计了。

    现在我们根据这些点调整一下我们的统计方法,对单词做一些预处理:

    import string

    path = '/Users/Hou/Desktop/Walden.txt'

    with open(path,'r') as text:
    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
    words_index = set(words)
    counts_dict = {index:words.count(index) for index in words_index}

    for word in sorted(counts_dict,key=lambda x: counts_dict[x],reverse=True):
    print('{} — {} times'.format(word,counts_dict[word]))
    • 第1行:引入了一个新的模块 string 。其实这个模块的用法很简单,我们可以试着把 string.punctuation 打印出来,其实这里面也仅仅是包含了所有的标点符号—— !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
    • 第4行:在文字的首位去掉了连在一起的标点符号,并把首字母大写的单词转化成小写;
    • 第5行:将列表用 set 函数转换成集合,自动去除掉了其中所有重复的元素;
    • 第6行:创建了一个以单词为键(key)出现频率为值(value)的字典;
    • 第7-8行:打印整理后的函数,其中 key=lambda x: counts_dict[x] 叫做 lambda 表达式,可以暂且理解为以字典中的值为排序的参数。