日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python遍歷文件夾內(nèi)文件并檢索文件中的中文內(nèi)容

作者:Pz_mstr 更新時(shí)間: 2022-05-12 編程語(yǔ)言

前言

有個(gè)需求,遍歷文件夾內(nèi)的文件,并搜索文件中是否存在特定關(guān)鍵字(中文)

代碼

import os 
import re
from os import path 

def cn_to_unicode(in_str, need_str=True, debug=False):
    out = []

    for s in in_str:
        # 獲得該字符的數(shù)值
        val = ord(s)
        # print(val)

        # 小于0xff則為ASCII碼,手動(dòng)構(gòu)造\u00xx格式
        if val <= 0xff:
            hex_str = hex(val).replace('0x', '').zfill(4)
            # 這里不能以u(píng)nicode_escape編碼,不然會(huì)自動(dòng)增加一個(gè)'\\'
            res = bytes('\\u' + hex_str, encoding='utf-8')
        else:
            res = s.encode("unicode_escape")

        out.append(res)
    
    # 調(diào)試
    if debug:
        print(out)
        print(len(out), len(out[0]), len(out[-1]))

    # 轉(zhuǎn)換為str類
    if need_str:
        out_str = ''
        for s in out:
            out_str += str(s, encoding='utf-8')
        return out_str
    else:
        return out

def scaner_file (url,key):
  file  = os.listdir(url)
  for f in file:
    real_url = path.join (url , f)
    if path.isfile(real_url):
      file_path = path.abspath(real_url)
      with open(file_path,encoding='utf8') as file_obj:
        contents = file_obj.read()
        res = re.findall(key, contents)
        if(res):
          print(contents)
          exit('Success!')
    elif path.isdir(real_url):
      scaner_file(real_url)
    else:
      print("其他情況")
      pass
  print(real_url)

chinese_key = "你好"
unicode_key = cn_to_unicode(chinese_key)
check_dir = "./result"

scaner_file(check_dir,unicode_key)  

原文鏈接:https://blog.csdn.net/qq_35544379/article/details/124531920

欄目分類
最近更新