python遍历文件夹内文件并检索文件中的中文内容
生活随笔
收集整理的這篇文章主要介紹了
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_strelse:return outdef 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("其他情況")passprint(real_url)chinese_key = "你好" unicode_key = cn_to_unicode(chinese_key) check_dir = "./result"scaner_file(check_dir,unicode_key)總結
以上是生活随笔為你收集整理的python遍历文件夹内文件并检索文件中的中文内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle查出连续5行,Oracle期
- 下一篇: java pdf 首页 缩略图_Java