如何用PythonDocx修复分解的文本以获得电子书的免费文本?

2024-05-03 22:12:48 发布

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

我正在尝试将我在网上找到的一本免费电子书编辑成易于阅读的Kindle文本,带有标题和完整的段落

一般来说,我对Python和编码非常陌生,所以我没有任何进展

每一行用回车符分隔,因此python将每一行视为一个单独的段落

基本上,需要做的是删除行间的空格和分隔符,这样文本在转换为MOBI或EPUB时不会中断

文本如下所示:

未格式化: enter image description here

应该是这样的:

格式: enter image description here

欢迎任何帮助


Tags: 文本编辑标题编码mobi格式epub电子书
1条回答
网友
1楼 · 发布于 2024-05-03 22:12:48

我使用了默认情况下未安装的docx库,您可以使用pip或conda:

pip install python-docx
conda install python-docx  channel conda-forge

安装后:

from docx import Document
doc = Document(r'path\to\file\pride_and_prejudice.docx')
all_text=[]
all_text_str=''

for para in doc.paragraphs:
    all_text.append(para.text)

all_text_str=all_text_str.join(all_text)

clean_text=all_text_str.replace('\n', '')   # Remove linebreaks
clean_text=clean_text.replace('  ', '')    # Remove even number of spaces (e.g. This usually eliminates non-spaces nicely, but you can tweak accordingly.

document = Document()
p = document.add_paragraph(clean_text)
document.save(r'path\to\file\pride_and_prejudice_clean.docx')

相关问题 更多 >