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

相关文章

TensorFlow用expand_dim()来增加维度的方法

TensorFlow中,想要维度增加一维,可以使用tf.expand_dims(input, dim, name=None)函数。当然,我们常用tf.reshape(input, sha...

python基础教程之python消息摘要算法使用示例

python基础教程之python消息摘要算法使用示例

复制代码 代码如下:#! /usr/bin/python'''      File    &nb...

pygame实现贪吃蛇游戏(上)

pygame实现贪吃蛇游戏(上)

本文实例为大家分享了pygame贪吃蛇游戏的具体代码,供大家参考,具体内容如下 1.准备工作 我们已经初始化了一个400*400的界面,为方便看我们的游戏,我们先在界面上画40*40的格...

Python利用PyExecJS库执行JS函数的案例分析

Python利用PyExecJS库执行JS函数的案例分析

  在Web渗透流程的暴力登录场景和爬虫抓取场景中,经常会遇到一些登录表单用DES之类的加密方式来加密参数,也就是说,你不搞定这些前端加密,你的编写的脚本是不可能...

用python3读取python2的pickle数据方式

问题一:TypeError: a bytes-like object is required, not 'str' 解决:该问题属于Python3和Python2的字符串兼容问题,数据文...