首页 > 解决方案 > Python在文本文件中写入巨大的字符串,每240个字符换行一次

问题描述

我需要将 word 文档转换为 html 代码,然后将其保存到 .txt 文件中,其中行数不超过 100 个字符(如果它们不在单独的行中,稍后会有一个过程不会提取超过 255 个字符行)。

到目前为止,我已经成功(尽管欢迎更好的解决方案)设法将 .docx 文件转换为 html 并将该变量部署到 .txt 文件中。但是,我无法弄清楚如何分隔线。是否有任何集成功能可以实现这一目标?

import mammoth

with open(r'C:\Users\uXXXXXX\Downloads\Test_Script.docx', "rb") as docx_file:
    result = mammoth.convert_to_html(docx_file)
    html = result.value # The generated HTML
    messages = result.messages # Any messages, such as warnings during conversion
    
with open(r'C:\Users\uXXXXXX\Downloads\Output.txt', 'w') as text_file:
    text_file.write(html)

标签: pythonhtmlmammoth

解决方案


在这种情况下,你可以这样做

html = "..."
i = 100
while i < len(html):
    html = html[:i] + "\n" + html[i:]
    i += 101

推荐阅读