如何使用python docx修复分解文本以获取电子书的免费文本?

问题描述 投票:0回答:1

我正在尝试将我在网上找到的免费电子书编辑成易于阅读的Kindle文本,包括标题和全文。

我对Python和编码一般还是很陌生,所以我没有任何进展。

每行都用Enter分隔,因此每行被python视为一个单独的段落。

基本上要做的是删除空格并在各行之间断开,以使文本在转换为MOBI或EPUB时不会断开。

文本看起来像这样:

Unformatted

并且应该看起来像这样:

Formatted

欢迎任何帮助!

python ms-word python-docx
1个回答
0
投票

我使用了默认情况下未安装的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')
© www.soinside.com 2019 - 2024. All rights reserved.