【问题标题】:Output format of an .epub conversion with utf-8 is bad使用 utf-8 进行 .epub 转换的输出格式不正确
【发布时间】:2019-03-18 11:29:48
【问题描述】:

我想将 epub 文件从 .epub 写入 .txt 并只获取文本,我找到了一个库来做。

import epub_conversion

f = open("demofile.txt", "a")
book = open_book("razvansividra.epub")
lines = convert_epub_to_lines(book)

for line in lines:
    f.writelines(str(line.encode("utf-8")))

一切都很好,但主要问题是输出是这种格式:

Carte electronic\xc4\x83 publicat\xc4\x83 cu sprijinul Ministerului Afacerilor Externe \xe2\x80\x93 Departamentul Politici pentru Rela\xc8\x9bia cu Rom\xc3\xa2nii de Pretutindeni.'b' 'b'

'b''b''

像“xc4”这样的字符我假设它们来自我的语言中的特殊字符,因为这本书是用我的语言写的。

【问题讨论】:

    标签: python utf-8 epub


    【解决方案1】:

    您正在进行不必要的编码/解码往返。

    检查这个小的交互式会话:

    >>> s = 'electronică'
    >>> b = s.encode('utf-8')
    >>> b
    b'electronic\xc4\x83'
    >>> str(b)
    "b'electronic\\xc4\\x83'"
    
    • 首先,您有一个字符串s,您对其进行编码 - 您将获得一个bytes 对象(注意b'...' 符号)。
    • 然后您对其调用 str(),这会将其再次转换回字符串 - 但不是通过解码,而是通过使用额外的引号和转义序列。
    • 当您调用f.writelines() 时,该字符串会在内部再次解码以将其写入磁盘。但由于都是 ASCII,最后一步并不明显。

    您应该确保从一开始就以正确的编码打开文件。 这样你就不用再使用line.encode('utf-8')了。

    因此:

    f = open("demofile.txt", "w", encoding="utf-8")
    

    然后:

    f.writelines(lines)
    

    请注意,如果您使用writelines,则无需执行for line in lines;它已经打算与可迭代的行一起使用。

    打开生成的文件时,请确保使用支持 UTF-8 的编辑器。 值得注意的是,像记事本这样的“简单”Windows 工具通常无法正确显示 UTF-8 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-23
      • 2017-12-11
      • 2014-09-08
      • 2021-02-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 2014-04-02
      相关资源
      最近更新 更多