python实现递归查找某个路径下所有文件中的中文字符

作者:weiguang1111 时间:2021-12-11 09:13:18 

本文实例为大家分享了python实现递归查找某个路径下所有文件中的中文字符,供大家参考,具体内容如下


# -*- coding: utf-8 -*-
# @ description:
# @ author:
# @ created: 2018/7/21

import re
import sys
import os

reload(sys)
sys.setdefaultencoding("utf8")

def translate(str):
 out = set()
 line = str.strip().decode('utf-8', 'ignore') # 处理前进行相关的处理,包括转换成Unicode等
 p2 = re.compile(ur'[^\u4e00-\u9fa5]') # 中文的编码范围是:\u4e00到\u9fa5
 zh = " ".join(p2.split(line)).strip()
 # zh = "\n".join(zh.split()) #dsds经过相关处理后得到中文的文本
 for s in zh.split():
   out.add(s) # 经过相关处理后得到中文的文本
 return out

def extract_file(path):
 result = set()
 try:
   f = open(path) # 打开文件
   lines = f.readlines()
   for line in lines:
     string = translate(line)
     if string:
       result.update(string)
 except Exception as e:
   pass
 return result

def extract(path):
 result = set()
 files = os.listdir(path)
 for file in files:
   if not file.startswith("."):
     if not os.path.isdir(path + "/" + file): # 判断是否是文件夹,不是文件夹才打开ssgsg判断是否是文件夹,不是文件夹才打开
       sub_file = extract_file(path + "/" + file)
       if sub_file:
         result.update(sub_file)
     else:
       print file
       child = extract(path + "/" + file)
       if child:
         result.update(child)
 return result

if __name__ == '__main__':
 path = "/Users/common"
 result = extract(path)
 res_file = open("result.txt", "w")
 for s in result:
   res_file.write(s + "\n")

来源:https://blog.csdn.net/weiguang111/article/details/81319421

标签:python,递归查找,中文字符
0
投稿

猜你喜欢

  • python目标检测yolo1 yolo2 yolo3和SSD网络结构对比

    2022-05-24 16:16:39
  • 如何使用python-opencv批量生成带噪点噪线的数字验证码

    2023-10-14 03:38:54
  • pandas.DataFrame 根据条件新建列并赋值的方法

    2022-09-06 05:51:05
  • golang中net的tcp服务使用

    2023-08-30 10:54:14
  • Python爬虫教程知识点总结

    2023-10-01 15:27:16
  • 基于python实现把json数据转换成Excel表格

    2021-02-20 05:22:04
  • SQLServer中数据库文件的存放方式,文件和文件组

    2012-01-05 18:56:33
  • 不要犯WEB字体编辑的10种错误

    2008-08-19 12:55:00
  • php操作SVN版本服务器类代码

    2023-09-08 07:22:41
  • Python内建类型str源码学习

    2021-12-24 22:24:33
  • 基于Python实现的微信好友数据分析

    2021-07-26 20:27:54
  • 如何用Python来理一理红楼梦里的那些关系

    2023-03-28 08:56:31
  • Python之lxml安装失败的解决

    2023-11-27 04:34:22
  • ASP同一站点下gb2312和utf-8页面传递参数乱码的终极解决方法

    2011-02-20 11:00:00
  • Python函数参数类型*、**的区别

    2022-03-01 18:09:54
  • Bootbox将后台JSON数据填充Form表单的实例代码

    2023-08-22 22:01:21
  • Python特效之数字成像方法详解

    2022-09-12 13:16:22
  • PHP PDOStatement::fetchColumn讲解

    2023-06-06 09:17:20
  • 网站改版常见问题答疑

    2008-08-22 18:31:00
  • Python 数据结构之队列的实现

    2021-11-28 15:27:26
  • asp之家 网络编程 m.aspxhome.com