1. 程式人生 > 程式設計 >python實現遞迴查詢某個路徑下所有檔案中的中文字元

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")

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。