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

yipeiwu_com5年前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 matrix和array的乘和加实例

1. 对于数组array 乘 就是对应位置的元素相乘: X1 = np.array([[1,2], [3, 4]]) X2 = X1 print X2*X1 [[ 1 4] [ 9...

python编程使用selenium模拟登陆淘宝实例代码

selenium简介 selenium 是一个web的自动化测试工具,不少学习功能自动化的同学开始首选selenium ,相因为它相比QTP有诸多有点: * 免费,也不用再为破解Q...

python开发简易版在线音乐播放器

在线音乐播放器,使用python的Tkinter库做了一个界面,感觉这个库使用起来还是挺方便的,音乐的数据来自网易云音乐的一个接口,通过urllib.urlopen模块打开网址,使用Js...

np.newaxis 实现为 numpy.ndarray(多维数组)增加一个轴

如下所示: >> type(np.newaxis) NoneType >> np.newaxis == None True np.newaxis 在使用和功...

Python中pygame安装方法图文详解

Python中pygame安装方法图文详解

本文实例讲述了Python中pygame安装方法。分享给大家供大家参考,具体如下: 这里主要描述一下我们怎样来安装pygame 可能很多人像我一样,发现了pygame是个好东东,但是就是...