您的位置:首页 > 编程语言 > Python开发

Python练手项目0006

2017-01-04 14:33 381 查看
本项目采用的是https://github.com/Yixiaohan/show-me-the-code中所提供的练习项目,所有代码均为原创,转载请注明,谢谢。

问题描述:练习0006的问题是有一个txt文本,里面有一些话,需要检索出里面每个词出现的频率,从而找出出现频率最高的关键词。

具体代码如下:

"""

Created on Wed Jan 04 13:58:39 2017

@author: sky

"""

"""

第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。

"""

import re

def import_word(target_file):

    file_object = open(target_file,'r')

    file_content = file_object.read()

    p = re.compile(r'[\W\d]*')

    word_list = p.split(file_content)

    word_dict = {}

    for word in word_list:

        if word not in word_dict:

            word_dict[word] = 1

        else:

            word_dict[word] += 1

    sort = sorted(word_dict.items(),key=lambda e :e[1],reverse=True)

    file = open('result.txt','w')

    file.write(str(word_dict))

    file.close()

    print "the most word in '%s' is '%s', it appears %s times" % (target_file, sort[0][0],sort[0][1])

    file_object.close()

if __name__ == "__main__":

    import_word('1.txt')

注意:

{}的作用是生成一个dict,而字典本身没有write的属性,所以需要自己建立一个txt文本,然后将dict 转化成str,才能存储

详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: