【发布时间】:2020-07-19 00:50:12
【问题描述】:
我一直在查看一些文档,但我所看到的关于 docx 的所有工作主要是针对在 word 文档中使用 文本。我想知道的是,是否有一种简单的方法可以从 HTML 或文本文档中获取文本,并将其导入到 word 文档中,然后进行批发? HTML/文本文档中的所有文本?好像不太喜欢这个字符串,太长了。
我对文档的理解是,您必须逐段处理文本。我想做的任务相对简单——但这超出了我的 Python 技能。我想在 word 文档上设置边距,然后将文本导入到 word 文档中,使其符合我之前指定的边距。
有人有什么想法吗?我发现以前的帖子都不是很有帮助。
import textwrap
import requests
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Inches
class DocumentWrapper(textwrap.TextWrapper):
def wrap(self, text):
split_text = text.split('\n\n')
lines = [line for para in split_text for line in textwrap.TextWrapper.wrap(self, para)]
return lines
page = requests.get("http://classics.mit.edu/Aristotle/prior.mb.txt")
soup = BeautifulSoup(page.text,"html.parser")
#we are going to pull in the text wrap extension that we have added.
#The typical width that we want tow
text_wrap_extension = DocumentWrapper(width=82,initial_indent="",fix_sentence_endings=True)
new_string = text_wrap_extension.fill(page.text)
final_document = "Prior_Analytics.txt"
with open(final_document, "w") as f:
f.writelines(new_string)
document = Document(final_document)
### Specified margin specifications
sections = document.sections
for section in sections:
section.top_margin = (Inches(1.00))
section.bottom_margin = (Inches(1.00))
section.right_margin = (Inches(1.00))
section.left_margin = (Inches(1.00))
document.save(final_document)
我得到的错误如下:
docx.opc.exceptions.PackageNotFoundError: Package not found at 'Prior_Analytics.txt'
【问题讨论】:
-
请帮忙?
标签: python beautifulsoup python-docx python-textprocessing