python遍历文件夹内文件并检索文件中的中文内容

前言

有个需求,遍历文件夹内的文件,并搜索文件中是否存在特定关键字(中文)

代码

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:
        # 获得该字符的数值
        val = ord(s)
        # print(val)

        # 小于0xff则为ASCII码,手动构造\u00xx格式
        if val <= 0xff:
            hex_str = hex(val).replace('0x', '').zfill(4)
            # 这里不能以unicode_escape编码,不然会自动增加一个'\\'
            res = bytes('\\u' + hex_str, encoding='utf-8')
        else:
            res = s.encode("unicode_escape")

        out.append(res)
    
    # 调试
    if debug:
        print(out)
        print(len(out), len(out[0]), len(out[-1]))

    # 转换为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)  
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值