如何在 python 中以 UTF-8 样式编写和编码我的文件?

杜威
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

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")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python中编码(utf8mb4)

如何在Python中修复损坏的utf-8编码?

如何解决:.py 文件无法从 .yaml 文件中解码用俄语和白俄罗斯语编写的 str。我正在使用 UTF-8 编码

Python-如何在UTF-8编码的文本中添加换行符?

如何在Python SOAPpy中设置UTF-8

如何在python中以utf-8格式写入文件名?

如何在 Python 中结合 .decode('utf-8') 和 .format() ?

如何从 Python 文件中读取单个 UTF-8 字符?

如何在改造android中设置utf-8编码?

如何在RStudio中检测非UTF-8编码

如何在golang中以UTF-8编码gob?

如何在Go中从编码转换为UTF-8?

如何在R中读取utf-8编码的文本

如何在Python中默认设置PYTHONUTF8环境变量以启用UTF-8编码?

如何在Python中将文件转换为utf-8?

在Python 3.5中编码utf-8和utf8之间的区别

如何在Python <3中将UTF-8编码的文本打印到控制台?

如何在Python <3中将UTF-8编码的文本打印到控制台?

Python DictWriter编写UTF-8编码的CSV文件

Ruby,Nokogiri:如何在整个nokogiri解析,erb模板和HTML文件编码中确保UTF8

如何在php文件中设置utf-8字符编码

如何在UTF-8编码文件中读写可打印的ASCII字符?

如何在Excel 2010中使用VBA查询UTF-8编码的CSV文件?

如何在Python3中正确产生和使用UTF-8 json?(带烧瓶和要求)

如何在Symfony XmlEncoder中设置编码UTF-8和xmlns属性

如何保存utf-8 JSON值并将其正确写入Python 3.8.2中的utf-8 txt文件?

如何在Python3中将UTF-8 CSV写入BytesIO中?

如何在以 utf-8 格式保存的文件的单行中读取和比较不同的单词?在蟒蛇?

如何在UTF-8中为Android中的不同字符集进行编码