Python,遍历文件夹中的文件并进行字数统计
发布时间:2020-12-20 11:23:13  所属栏目:Python  来源:网络整理 
            导读:我是 python的新手,我需要编写一个脚本来计算目录中所有txt文件中的所有单词.这是我到目前为止,只是打开一个txt文件时其他工作,但当我进入一个目录它失败.我知道我需要在某个地方追加,我尝试了几种不同的方式,但运气不佳. *编辑我希望将结果集中在一起.到目
                
                
                
            | 
                         
 我是 
 python的新手,我需要编写一个脚本来计算目录中所有txt文件中的所有单词.这是我到目前为止,只是打开一个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','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") 
 那么你不需要在路径之前和之后包含’ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
