Python:缩进输出文本

时间:2018-05-05 11:26:13

标签: python-3.x text terminal output text-manipulation

我正在编写一个脚本,它可以做的一件事就是从在线资源中检索词典定义,例如:en.wiktionary.org

  

我正在使用制表符来在每个字符串前面添加缩进,以便将字典定义与输出的其余部分分开,就像这个引号框一样。
  

所以目前它看起来像这样:

代码:

Args = input('Define: ').split()
Word = Args[0]
Type = Args[1]
Many = Args[2]

print('\n\t'+ '\"'+Word+'\" '+Type)
print('\t\t'+Define(Word,Type,Many))

当输出相对较短时,哪种方法可以正常工作:

输入#1:

Define: dog verb 2

输出#1:

    "dog" verb
        1: To pursue with the intent to catch.
        2: To fasten a hatch securely.

但不是那么多,当文本溢出到下一行时:

输入#2:

Define: dog noun 2

输出#2:

    "dog" noun
        1: A domesticated carnivorous mammal (Canis familiaris) related to the foxes 
and wolves and raised in a wide variety of breeds.
        2: Any of various carnivorous mammals of the family Canidae, such as the 
dingo.

最后一个所需的输出看起来更像是这样:

输出#3:

    "dog" noun
        1: A domesticated carnivorous mammal (Canis familiaris) related to the foxes 
        and wolves and raised in a wide variety of breeds.
        2: Any of various carnivorous mammals of the family Canidae, such as the 
        dingo.

我如何使用动态内容以编程方式强制执行这种格式化?

2 个答案:

答案 0 :(得分:0)

非常确定textwrap会做你想做的事。

答案 1 :(得分:0)

我很确定你必须定义要包装的文本长度。我使用100的长度。

import textwrap

print('\t\t' + '\n\t\t'.join(textwrap.wrap(Define(Word,Type,Many), width=100)))

希望它会有所帮助!