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

yipeiwu_com6年前Python基础

本文实例为大家分享了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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Numpy之reshape()使用详解

Numpy之reshape()使用详解

如下所示: Numpy中reshape的使用方法为:numpy.reshape(a, newshape, order='C') 参数详解: 1.a: type:array_like(伪数...

Python日志模块logging简介

Python日志模块logging简介

logging分为4个模块: loggers, handlers, filters, and formatters. ●loggers: 提供应用程序调用的接口 ●handlers: 把...

Python实现ping指定IP的示例

Python实现ping指定IP的示例

贴代码: import os import sys iplist = list() ip = '192.168.1.11' # ip = '172.24.186.191'...

python适合人工智能的理由和优势

Python借助AI和数据科学,目前已经攀爬到了编程语言生态链的顶级位置,可以说Python基本上与AI已经紧密捆绑在了一起了。为什么人工智能开发要使用到python语言?小编认为基于以...

python解析xml文件操作实例

本文实例讲述了python解析xml文件操作的实现方法。分享给大家供大家参考。具体方法如下: xml文件内容如下: <?xml version="1.0" ?&...