我是靠谱客的博主 无限康乃馨,这篇文章主要介绍python 统计文本文件中单词出现的个数,现在分享给大家,希望可以做个参考。

如题:

#!/usr/bin/env python
# encoding: utf-8

import re

with open('a.txt', 'r') as f:
    dictResult = {}

    # Find the letters each line
    for line in f.readlines():
        listMatch = re.findall('[a-zA-Z]+', line.lower()) # remember to lower the letters

    # Count
        for eachLetter in listMatch:
            eachLetterCount = len(re.findall(eachLetter, line.lower()))
            dictResult[eachLetter] = dictResult.get(eachLetter, 0) + eachLetterCount

    # Sort the result
    result = sorted(dictResult.items(), key=lambda d: d[1], reverse=True)
    for each in result:
        print each


最后

以上就是无限康乃馨最近收集整理的关于python 统计文本文件中单词出现的个数的全部内容,更多相关python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(110)

评论列表共有 0 条评论

立即
投稿
返回
顶部