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

相关文章

python os.path模块常用方法实例详解

os.path模块主要用于文件的属性获取,在编程中经常用到,以下是该模块的几种常用方法。更多的方法可以去查看官方文档:http://docs.python.org/library/os....

Python交互环境下实现输入代码

Python交互环境下实现输入代码

Iamlaosong文 Python交互环境的提示符是“>>>”,命令行模式下输入python命令就可以进入这个交互环境进行交互会话。 在windows中,除了在she...

django+mysql的使用示例

django+mysql的使用示例

Django中每一个模型model都对应于数据库中的一张表,每个模型中的字段都对应于数据库表的列。方便的是,django可以自动生成这些create table, alter table...

python实现excel读写数据

本文实例为大家分享了python操作EXCEL的实例源码,供大家参考,具体内容如下 读EXCEL的操作:把excel的数据存储为字典类型 #coding=utf8 #导入读ex...

使用Python的内建模块collections的教程

collections是Python内建的一个集合模块,提供了许多有用的集合类。 namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: &g...