【问题标题】:Is there a way to write formatted text from Python?有没有办法从 Python 编写格式化文本?
【发布时间】:2013-04-16 05:39:51
【问题描述】:

如果您正在使用 python 写入文件,有没有办法使文本的某些部分变为粗体、斜体或下划线?

我试过了:

test = '/location/tester.rtf'
out_file = open(test,'w')
out_file.write('is this {\bold}?')
out_file.close() #thanks to the comment below

是否可以通过 python 编写 FORMATTED TEXT,如粗体、斜体或带下划线的文本?我觉得 .rtf 是最基本的格式化文本,但如果我错了,请纠正我

【问题讨论】:

  • 1) 在标题中提出真正的问题:“如何用 Python 编写 RTF 文件?” (或任何所需的格式;例如 DOC、DOCX、Open Office 使用的任何格式等)和 2) 包括错误症状(通常包括错误消息)。
  • 你必须out_file.close()才能再次打开它。

标签: python text format fwrite


【解决方案1】:

刚刚玩弄了这个假设的 MS 字,我发现您需要将文档包装在“{}”中并定义文档类型,然后以“\b”开始粗体并以“\b0”结束。一个例子是

test = 'tester.rtf'
out_file = open(test,'w')
out_file.write("""{\\rtf1
This is \\b Bold  \\b0\line\
}""")
out_file.close() #thanks to the comment below

注意双 '\' 因为 python 对 '\b' 和 '\r' 有特殊含义。

完整信息来自http://www.pindari.com/rtf1.html,其中还描述了斜体、字体等。

如果这对你有用,请告诉我。

【讨论】:

  • Hi max K。很好的答案,如果我们希望变量写入 out_file.write 怎么办。
猜你喜欢
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 2019-11-27
  • 2020-06-27
相关资源
最近更新 更多