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

yipeiwu_com4年前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设计】。

相关文章

在Python中合并字典模块ChainMap的隐藏坑【推荐】

在Python中合并字典模块ChainMap的隐藏坑【推荐】

在Python中,当我们有两个字典需要合并的时候,可以使用字典的 update 方法,例如: a = {'a': 1, 'b': 2} b = {'x': 3, 'y': 4} a....

Python的Django应用程序解决AJAX跨域访问问题的方法

引子 使用Django在服务器端写了一个API,返回一个JSON数据。使用Ajax调用该API: <!DOCTYPE HTML> <html> <he...

Django model update的多种用法介绍

Django model update的多种用法介绍

model update常规用法 假如我们的表结构是这样的 class User(models.Model): username = models.CharField(max_le...

python实现简单的单变量线性回归方法

python实现简单的单变量线性回归方法

线性回归是机器学习中的基础算法之一,属于监督学习中的回归问题,算法的关键在于如何最小化代价函数,通常使用梯度下降或者正规方程(最小二乘法),在这里对算法原理不过多赘述,建议看吴恩达发布在...

关于tf.reverse_sequence()简述

tf.reverse_sequence()简述 在看bidirectional_dynamic_rnn()的源码的时候,看到了代码中有调用 reverse_sequence()这一方法,...