使用Python查找文件中的非ASCII行或字符

使用Python查找文件中的非ASCII行或字符,python,encoding,utf-8,ascii,argparse,Python,Encoding,Utf 8,Ascii,Argparse,我正在尝试编写一个脚本,以找出文件中的哪一行包含非ASCII字符(特别是“windows-1252”)。我写这个脚本是希望当它到达包含错误字符的行时会出错: import argparse FLOW_FILE_ENCODING = "windows-1252" def get_failed_character(filepath): with open(filepath, encoding=FLOW_FILE_ENCODING) as f: for

我正在尝试编写一个脚本,以找出文件中的哪一行包含非ASCII字符(特别是“windows-1252”)。我写这个脚本是希望当它到达包含错误字符的行时会出错:

import argparse

FLOW_FILE_ENCODING = "windows-1252"


def get_failed_character(filepath):
    with open(filepath, encoding=FLOW_FILE_ENCODING) as f:
        for num, line in enumerate(f, 1):
            try:
                line.strip()
            except:
                print(num)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Parse file."
    )
    parser.add_argument("--file", help="File name")
    args = parser.parse_args()

    get_failed_character(args.file)
def get_failed_character(filepath):
    with open(filepath, encoding=FLOW_FILE_ENCODING, errors='replace') as f:
        for num, line in enumerate(f, 1):
            if '\ufffd' in line:  # 0xFFFD is the Unicode replacement character
                print(num)

要明确的是,cp1252不是“ASCII形式”,它是ASCII超集,所以您在这里寻找的是非cp1252

这里最简单的解决方案是使用
errors='replace'
模式,然后在每一行中搜索替换字符:

import argparse

FLOW_FILE_ENCODING = "windows-1252"


def get_failed_character(filepath):
    with open(filepath, encoding=FLOW_FILE_ENCODING) as f:
        for num, line in enumerate(f, 1):
            try:
                line.strip()
            except:
                print(num)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Parse file."
    )
    parser.add_argument("--file", help="File name")
    args = parser.parse_args()

    get_failed_character(args.file)
def get_failed_character(filepath):
    with open(filepath, encoding=FLOW_FILE_ENCODING, errors='replace') as f:
        for num, line in enumerate(f, 1):
            if '\ufffd' in line:  # 0xFFFD is the Unicode replacement character
                print(num)
我会注意到,这不是一种特别安全的检查方式;cp1252具有除五个可能字节之外的所有字节的映射,因此其他ASCII超集编码中的文本很可能会通过此测试(它只会为ASCII范围之外的字节生成乱码)。这就是为什么ASCII超集(除了UTF-8)是一个如此糟糕的主意;在不提前知道编码的情况下,您可能会成功地将文本解码为垃圾,因为大多数超集可以将一种编码中的数据映射到自己,而不会出错,这对人类来说只是胡言乱语。你需要知道真正的编码,否则你只是在做错误的猜测


如果您的目标是查找非ASCII cp1252字符(您的问题的措辞有点不清楚),这仍然有效,只需将参数更改为
encoding='ASCII'
,以便所有非ASCII字符都成为替换字符。

您的“错误字符”概念已关闭。您的输入文件到底是什么样子的?您希望发生什么?我希望脚本在包含非windows-1252字符的行上出错,以便我可以看到它在哪一行上。我已将文件格式添加到问题中,您对该脚本有何疑问?有什么不起作用的吗?