美文网首页
Python 练习册 0004、0006题 (统计文本)

Python 练习册 0004、0006题 (统计文本)

作者: 海上牧云l | 来源:发表于2017-04-21 22:39 被阅读41次

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

    这里把最重要的词当作出现频率最高的词来查找

    答案

    from collections import Counter
    
    # 统计某一单词出现次数
    with open('find.txt', 'r') as f:
        word_list = f.read().split(' ')
        word = input('输入要查找到的单词:')
        num = Counter(word_list).get(word)
        if not num:
            num = 0
        print('{}: {}'.format(word, num))
    
    
    # 统计日记文本中最重要的词
    with open('find.txt') as f:
        word_list = f.read().split(' ')
        top_word = Counter(word_list).most_common(1)[0]
    
        print('此文本中频率最高的词是:{}'.format(list(top_word)[0]))
    

    相关文章

      网友评论

          本文标题:Python 练习册 0004、0006题 (统计文本)

          本文链接:https://www.haomeiwen.com/subject/ifyjzttx.html