python循环遍历word_Python,遍历文件夹中的文件并执行word con

我是python新手,我需要编写一个脚本来计算目录中所有txt文件中的所有单词。这就是我目前所拥有的,else在打开一个txt文件时起作用,但是当我进入一个目录时,它就失败了。我知道我需要一个附加的地方,我尝试了几种不同的方法,但运气不佳。在

*编辑我想把结果集中在一起。到目前为止,它有两个独立的结果。我试着列一张新的单子,并在上面加上计数器。但它坏了。再次感谢,这是一个很好的社区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: ")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值