Skip to content Skip to sidebar Skip to footer

Fonts Formatting In Python Output

I am trying to change the output fonts in python. I have read you can use Tkinter package but it is too complicated for me. I am trying to parse two documents, one plain text and t

Solution 1:

It seems likely that there is an ANSI escape code in your vera_en2.txt that sets the font to italic. Open the file or print the repr() of the first line of that file to verify this.

Apparently you are working in an ANSI compatible terminal already, or you wouldn't be seeing italic text. So, you should be able to reset the font with print("\033[0m"), and enable italics again with print("\033[3m").

If this all seems too esoteric, I recommend using colorama.

Edit:

Ah, so you want to write an RTF file with some italic text. And your .txt files aren't actually .txt files. That's completely different from what I explained above.

By analyzing the plain text of an actual rtf I came up with this small example. It generate a small rtf file with normal, italic and bold words; \i and \b are used to toggle these formats.

# open file
myrtf = open('myrtf.rtf', 'w ')

# write some necessary header info
myrtf.write(r'{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}')

# write the actual text - notice I'm using raw strings (r'')
myrtf.write(r'normal \i italic \i0 \b bold \b0 normal\n')

# write end of file stuff
myrtf.write(r'}\n\x00')

# close file
myrtf.close()

Also, answering the other question; getting italics in the console might be difficult, most terminals just don't support it.

To adapt the above code sample to the problem in your question:

L1 = open ('file1.txt','r')
L2 = open ('file2.txt','r')
O = open ('output.rtf','w')

# write header
O.write(r'{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}')

for line in L1:
    line2 = r"\i  " + L2.readline() + r" \i0\line\par"# make text from L2 italicprint(line, end='')
    print(line2)
    O.write(line)
    O.write(line2)

# close rtf
O.write(r'}\n\x00')

L1.close()
L2.close()
O.close()

Another addition:

Based on our discussion in the comments, here's one way to do it by writing a html file instead of rtf:

L1 = open ('file1.txt','r')
L2 = open ('file2.txt','r')
O = open ('output.html','w')

# write header
O.write(r'<html><head><title>Foobar</title></head><body><table>')

for line in L1:
    line2 = r"<i>" + L2.readline() + r"</i></br>"# make text from L2 italic
    O.write("<tr>")
    O.write("<td>%s</td>" % line)
    O.write("<td>%s</td>" % line2)
    O.write("</tr>\n")

# footer
O.write(r'</table></body></html>')

L1.close()
L2.close()
O.close()

Here you can see the result when file1.txt and file2.txt are Old English and modern versions of a verse from Beowulf.

Post a Comment for "Fonts Formatting In Python Output"