Regex: convert i t a l i c s and b_o_l_d to *italics* and **bold**

Viewed 121

I have a text file with spaces instead of italic formatting:

"Zaratustra į minią šitaip kreipės:
"A š   a n t ž m o g į   j u m s   s k e l b t i   n o r i u. Žmogus yra būtybė, kurią įveikti reikia. Ką esat jūs padarę, kad įveiktas jis būtų?

And it should become like this:

"Zaratustra į minią šitaip kreipės: "Aš antžmogį jums skelbti noriu. Žmogus yra būtybė, kurią įveikti reikia. Ką esat jūs padarę, kad įveiktas jis būtų?

Then there's this instead of bold text:

Ž_m_o_g_u_s___n_e_t_u_r_i___j_a_u_s_t_i___k_e_r_š_t_o: štai tiltas mano tas viltin didžiausion ir ta vaivorykštė po darganų ilgų ir vėjų.

Should be like this (I kind of have a solution for this:

Žmogus neturi jausti keršto: štai tiltas mano tas viltin didžiausion ir ta vaivorykštė po darganų ilgų ir vėjų.

I currently have this script:

import re
import argparse

parser = argparse.ArgumentParser(description="Removes shit from ripped books")
parser.add_argument("-i", "--input", help="inputfile.txt")
parser.add_argument("-o", "--output", help="outputfile.md")
args = parser.parse_args()



fileopen = open(args.input, "r")

text = fileopen.read()

# remove these bits
text = text.replace("<I>", "")
text = text.replace("</I>", "")

#Convert to Bold
triple_underscore_re = re.compile(r'_{3}')
text = re.sub(triple_underscore_re, "_ ", text)

underscore_to_bolt_re = re.compile(r'((._)+)')
text = re.sub(underscore_to_bolt_re, r'**\1**', text)

underscore_to_nil_re = re.compile(r'_')
text = re.sub(underscore_to_nil_re, "", text)

out = open(args.output, "w")
out.write(text)

Conversion to bold sort of works but always misses some characters, mostly the last character of the string.

Can someone recommend how to tackle this problem?

1 Answers

The main problem is with underscore_to_bolt_re = re.compile(r'((._)+)') that matches up to the last letter without matching it.

You may replace it with

text = re.sub(r'[^_](?:_[^_])+', r'**\g<0>**', text)

See the regex demo. Details:

  • [^_] - any char other than _
  • (?:_[^_])+ - one or more repetitions of a _ and then a char other than _.
Related