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连接FTP服务器的实现方法

    2022-04-07 14:34:03
  • 酷! 程序员用Python带你玩转冲顶大会

    2022-02-20 11:56:08
  • BOM中location对象的属性和方法

    2024-04-16 09:55:07
  • 用好FrontPage2003的九大功能

    2008-02-21 14:29:00
  • 微软建议的ASP性能优化28条守则(3)

    2008-02-24 16:30:00
  • PHP+redis实现添加处理投票的方法

    2023-11-22 04:38:19
  • 跟老齐学Python之dict()的操作方法

    2022-05-12 16:54:43
  • 用python求一重积分和二重积分的例子

    2021-09-30 10:01:19
  • PHP bin2hex()函数基础实例讲解

    2023-06-12 16:30:44
  • python删除特定文件的方法

    2023-07-13 23:29:36
  • Python模拟百度登录实例详解

    2023-07-18 19:06:46
  • Pandas中的unique()和nunique()区别详解

    2022-02-06 21:51:05
  • 为Python的Tornado框架配置使用Jinja2模板引擎的方法

    2022-07-19 03:49:07
  • django数据模型on_delete, db_constraint的使用详解

    2023-02-16 04:48:06
  • MySql分表、分库、分片和分区知识深入详解

    2024-01-20 19:11:03
  • JavaScript中cookie工具函数封装的示例代码

    2024-04-25 13:16:01
  • 详解用pyecharts Geo实现动态数据热力图城市找不到问题解决

    2022-02-04 14:10:29
  • asp金额大小写转换完全无错版

    2007-09-26 09:38:00
  • Python如何实现小程序 无限求和平均

    2023-04-13 20:07:40
  • python 寻找list中最大元素对应的索引方法

    2021-02-16 07:37:52
  • asp之家 网络编程 m.aspxhome.com