我打算做什么?
要在 Windows 文件系统上的一组文件中搜索 alphabetic 字符串列表(大约 25K 个不同大小和扩展名的主要是纯文本文件,最大文件不超过几 MB尺寸)
我做了什么来实现这个目标?
for each_file in files:
file_read_handle = open(each_file,"rb")
file_read_handle.seek(0) #ensure you're at the start of the file
first_char = file_read_handle.read(1) #get the first character
if first_char:
file_read_content_mappd = mmap.mmap(file_read_handle.fileno(), 0, access=mmap.ACCESS_READ)
if re.search(br'(?i)T_0008X_WEB', file_read_content_mappd):
file_write_content = ('Text T_0008X_WEB found in {}'.format(each_file))
file_write_handle.write(file_write_content)
file_write_handle.write("\n")
file_write_handle.close()
对于以二进制模式打开的文件中的硬编码文本搜索(参见行 T_0008X_WEB),这段代码工作得很好 ("rb ") 以避免 UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 776: character maps to undefined 错误。
但是,当尝试通过用这样的变量替换硬编码值来搜索值列表时-if re.search('br\' (?i)' + regex_search_str_byte + '\'', file_read_content_mappd):
, 一直面临以下问题-
- 使用时:
re.search('br\'(?i)' + regex_search_str + '\'', file_read_content_mappd):
得到错误:文件是二进制格式和搜索文本是字符串类型 - 使用时:
re.search(regex_search_str_byte, file_read_content_mappd):
遇到问题:找不到匹配项,因为即使是正则表达式字符 br'(?i) 也被认为是字节转换搜索文本的一部分
请求有关如何执行字节转换文本正则表达式搜索值列表、二进制模式打开文件读取的指导?
最佳答案
使用
re.search(regex_search_str_byte, file_read_content_mappd, flags=re.I)
re.I
标志可以作为参数传递给 re.search
方法。 br
前缀不是必需的,因为它们用于修改字符串文字,而您使用的是变量。
关于Python 3.6.1 |正则表达式搜索具有特殊字符的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46189604/