【问题标题】:Ansi to UTF-8 using python causing errorAnsi 到 UTF-8 使用 python 导致错误
【发布时间】:2014-09-13 14:46:30
【问题描述】:

当我尝试编写一个将 Ansi 转换为 UTF-8 的 python 程序时,我发现了这个

https://stackoverflow.com/questions/14732996/how-can-i-convert-utf-8-to-ansi-in-python

将 UTF-8 转换为 Ansi。

我认为只要颠倒顺序就可以了。所以我编码了

file_path_ansi = "input.txt"
file_path_utf8 = "output.txt"

#open and encode the original content
file_source = open(file_path_ansi, mode='r', encoding='latin-1', errors='ignore')
file_content = file_source.read()
file_source.close

#write 
file_target = open(file_path_utf8, mode='w', encoding='utf-8')
file_target.write(file_content)
file_target.close

但它会导致错误。

TypeError: file<> takes at most 3 arguments <4 given>

所以我改变了

file_source = open(file_path_ansi, mode='r', encoding='latin-1', errors='ignore')

file_source = open(file_path_ansi, mode='r', encoding='latin-1')

然后它会导致另一个错误:

TypeError: 'encoding' is an invalid keyword arguemtn for this function

我应该如何修复我的代码来解决这个问题?

【问题讨论】:

    标签: python utf-8 character-encoding


    【解决方案1】:

    您正在尝试在 Python 2 上使用 open() function 的 Python 3 版本。在主要版本之间,I/O 支持已经过大修,支持更好的编码和解码。

    您可以在 Python 2 中获得与 io.open() 相同的新版本。

    我会使用shutil.copyfileobj() function 进行复制,因此您不必将整个文件读入内存:

    import io
    import shutil
    
    with io.open(file_path_ansi, encoding='latin-1', errors='ignore') as source:
        with io.open(file_path_utf8, mode='w', encoding='utf-8') as target:
            shutil.copyfileobj(source, target)
    

    不过要小心;大多数谈论 ANSI 的人指的是Windows codepages 中的一个;您可能确实在 CP(代码页)1252 中有一个文件,几乎,但与ISO-8859-1 (Latin 1) 不完全相同。如果是这样,请使用cp1252 而不是latin-1 作为encoding 参数。

    【讨论】:

    • CP1251 是西里尔文,CP1252 类似于 ISO 8859-1。
    • @MartijnPieters 谢谢!但是我怎么知道我的 input.txt 是用 cp1252 还是 Latin 1 写的呢?
    • @user3123767:Latin-1 的控制码在 80-9F 范围内,而 CP-1252 有更多字符(请参阅Wikipedia page on CP-1252,查找表格行8_ 和@ 987654335@)。如果解码为 cp1252 的文本有效且有意义,那么就去做吧。无论如何,很少有文本(如果有)使用 Latin-1 控制代码。
    • 为了完整起见,还请导入shutils - 如果是相反的方式,错误的可能性更大,因为UTF8 是ANSI 的超集。因此,如果您尝试相反的方式:使用 io.open(csv_file_path, encoding='utf8', errors='ignore') 作为源:使用 io.open(csv_file_path_ansi, mode='w', encoding='cp1252', errors='ignore') 作为目标:shutil.copyfileobj(source, target)
    • @Wolfgang:这个答案专门解决了问题使用的编解码器组合。这完全取决于您的实际数据,什么样的编解码器才有意义。
    猜你喜欢
    • 2014-07-02
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2011-11-20
    • 2023-03-19
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多