Python,遍历文件夹中的文件并进行字数统计

标签 python

我是 python 的新手,我需要编写一个脚本来计算目录中所有 txt 文件中的所有单词。这是我到目前为止所拥有的,其他的在打开一个 txt 文件时有效,但是当我进入一个目录时它失败了。我知道我需要在某处追加,我已经尝试了几种不同的方法,但运气不佳。

*edit 我希望将结果集中在一起。到目前为止,它有 2 个独立的结果。我尝试制作一个新列表并在其上附加计数器。但它坏了。再次感谢,这是一个很好的社区

import re
import os
import sys
import os.path
import fnmatch
import collections

def search( file ):

    if os.path.isdir(path) == True:
        for root, dirs, files in os.walk(path):
            for file in files:
                words = re.findall('\w+', open(file).read().lower())
                ignore = ['the','a','if','in','it','of','or','on','and','to']
                counter=collections.Counter(x for x in words if x not in ignore)
                print(counter.most_common(10))

    else:
        words = re.findall('\w+', open(path).read().lower())
        ignore = ['the','a','if','in','it','of','or','on','and','to']
        counter=collections.Counter(x for x in words if x not in ignore)
        print(counter.most_common(10))

path = input("Enter file and path, place ' before and after the file path: ")
search(path)

raw_input("Press enter to close: ")

最佳答案

将第 14 行更改为:

words = re.findall('\w+', open(os.path.join(root, file)).read().lower())

此外,如果您将输入行替换为

path = raw_input("Enter file and path")

那么你就不需要在路径前后包含'

关于Python,遍历文件夹中的文件并进行字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9082099/

相关文章:

python - 这两种为 sklearn 分类器过滤 Pandas 数据帧的方法有什么区别?

python - 制作散点轮廓

Python 和 csv.writer : Open in every loop or keep open?

python - 如何在pygame中检测Sprite和Rect之间的碰撞

python - 用于在远程服务器上运行命令的交互式 Python 脚本

python - 如何使用 SQLAlchemy 和 session 进行更新?

python - 如何在python中按条件排序

Python 脚本不更新变量

python - 如何在 SQLAlchemy 中连接两个表中的数据?

python - 无法在 Mac OS X 中正确运行 odoo