0

I'm writing a script and one of the things it can do is retrieve dictionary definitions from online resources such as: en.wiktionary.org.

I'm using the tab character to prepend each string with an indent, so as to separate the dictionary definitions from the rest of the output, much like this quote box.
 


So currently it looks something like this:

Code:

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))

Which works fine, when the output is relatively short:

Input#1:

Define: dog verb 2

Output#1:

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

But not so much, when the text overflows onto the next line:

Input#2:

Define: dog noun 2

Output#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.

The desired output for that last one, would look more like this:

Output#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.

How could I programatically enforce that kind of formatting with dynamic content?

voices
  • 495
  • 6
  • 20
  • Not a full solution, but take a look at the pretty print library, built-in to Python: https://docs.python.org/3/library/pprint.html – darthbith May 05 '18 at 11:28
  • You'd have to manually cut the line after a certain number of characters, then prefix each line with tabs. Since there's no way, afaik, to get console width, you won't be able to make it "reactive". Maybe cut every 80 characters? – Carcigenicate May 05 '18 at 11:29
  • @Carcigenicate Actually, if you `import shutil`, you can `shutil.get_terminal_size()`. It will output something like `os.terminal_size(columns=238, lines=72)`. That much I do know. – voices May 05 '18 at 11:50
  • @user3155368 Oh, interesting. I typically work with Java and these isn't a great way to do it there. Assumed it would be the same. Anyways, the you can just cut the line after `columns` after taking into consideration the tabs, then add the tabs. – Carcigenicate May 05 '18 at 11:54

2 Answers2

0

Pretty sure textwrap will do what you want.

offby1
  • 6,767
  • 30
  • 45
0

I'm pretty sure you have to define the length of text to wrap. I used length of 100.

import textwrap

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

Hope it will help!

MaNKuR
  • 2,578
  • 1
  • 19
  • 31