使用Python搜索Unicode文件

And*_*ton 1 python unicode encoding

建立

我正在编写一个脚本来处理和注释Visual Studio中的构建日志.构建日志是HTML,从我所知,Unicode(UTF-16?)也是如此.这是其中一个文件的片段:

c:\ anonyfolder\anonyfile.c(17169):警告C4701:可能未初始化的局部变量'object_adrs2'使用
c:\ anonyfolder\anonyfile.c(17409):警告C4701:可能未初始化的局部变量'pclcrd_ptr'使用
c:\ anonyfolder\anonyfile.c(17440):警告C4701:使用了未初始化的局部变量'object_adrs2'

该文件的前16个字节如下所示:

feff 003c 0068 0074 006d 006c 003e 000d

文件的其余部分也充满了空字节.

我希望能够对这些文件执行字符串和正则表达式搜索/匹配.但是,当我尝试以下代码时,我收到一条错误消息.

buildLog = open(sys.argv[1]).readlines()

for line in buildLog:
    match = u'warning'
    if line.find(match) >= 0:
        print line
Run Code Online (Sandbox Code Playgroud)

错误消息:

回溯(最近调用最后一次):
文件"proclogs.py",第60行,
如果line.find(匹配)> = 0:
UnicodeDecodeError:'ascii'编解码器无法解码位置0中的字节0xff:序数不在范围内(128)

显然它正在阻塞文件开头的0xff字节0xfeff.如果我跳过第一行,我没有匹配:

buildLog = open(sys.argv[1]).readlines()

for line in buildLog[1:]: # Skip the first line.
    match = u'warning'
    if line.find(match) >= 0:
        print line
Run Code Online (Sandbox Code Playgroud)

同样,使用非Unicode match = 'warning'不会产生任何结果.

如何在Python中使用字符串和正则表达式来移植搜索Unicode文件?另外,我该怎么做才能重建原始文件?(目标是能够在警告线上编写注释而不会破坏文件.)

Ale*_*erg 7

尝试使用编解码器包:

import codecs
buildLog = codecs.open(sys.argv[1], "r", "utf-16").readlines()
Run Code Online (Sandbox Code Playgroud)

此外,您可能会遇到print语句的问题,因为它可能会尝试将字符串转换为您的控制台编码.如果您要打印以供审核,可以使用,

print repr(line)
Run Code Online (Sandbox Code Playgroud)