如何在python中以UTF8样式编写和编码文件?

2024-09-30 16:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

import io

def write_ngrams(table, filename):

    with io.open(filename, "w") as file:
        for i in table:
            outputstring=(('%d %s\n' % (table[i], i)))
            encoded = outputstring.encode("utf-8")
            file.write(encoded)

tabel = ngram_table('hiep, hiep, hoera!', 3, 0) // these are not really interesting for now

write_ngrams(tabel, "testfile3.txt")

我在file.write(encoded)行收到一个错误,该行声明如下:

TypeError: write() argument must be str, not bytes.

但是我的任务是:输出必须使用utf8编码

这意味着输出的形式应该是b'..'

用我尝试过的方法,我只得到没有编码或错误的字符串。然而,当我使用print(encoded)时,我确实会收到UTF-8编码的输出,但是当我将其写入一个文件时,编码消失了,或者我得到了一个错误

任何提示都将不胜感激


Tags: ioimport编码for错误tablenotfilename
1条回答
网友
1楼 · 发布于 2024-09-30 16:21:34

您可以将字符串传递给write()&;打开编码设置为utf-8的文件

import io

def write_ngrams(table, filename):

    with io.open(filename, "w", encoding='utf-8') as file:
        for i in table:
            outputstring=(('%d %s\n' % (table[i], i)))
            file.write(outputstring)

tabel = ngram_table('hiep, hiep, hoera!', 3, 0) // these are not really interesting for now

write_ngrams(tabel, "testfile3.txt")

相关问题 更多 >