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编码的输出,但是当我将其写入一个文件时,编码消失了,或者我得到了一个错误
任何提示都将不胜感激
您可以将字符串传递给
write()
&;打开编码设置为utf-8
的文件相关问题 更多 >
编程相关推荐