Enclose greek sentence between tag or find and replace part of sentence that contains greek characters

Viewed 42

I am trying to find a way to enclose sentences using greek characters in special tags (in this case LaTeX but it doesn't matter). So given my input text:

inputtext = "some english text ῍Ενθεσις τοῦ Ψαλτής and then english again"

I would like to achieve this:

results = "some english text \textgreek{῍Ενθεσις τοῦ Ψαλτής} and then english again"

After some hours I came up with this solution that almost work:

import re 
inputtext = "some english text ῍Ενθεσις τοῦ Ψαλτής and then english again" 
t = re.findall('[α-ωΑ-Ω]',inputtext) 
beg = inputtext.find(t[0]) 
end = inputtext.rfind(t[-1]) + 1 
results = "".join((inputtext[:beg]+"\textgreek{"+inputtext[beg:end]+"}"+inputtext[end:]))


In [50]: results                                                                                  
Out[50]: 'some english text ῍\textgreek{Ενθεσις τοῦ Ψαλτής} and then english again'

Then the topical question arose to my mind, is there a better solution? Maybe using only regex? The current solution seems to ignore the polytonic greek characters ῍ and of course it works only if there is one greek sentence per sentence.

1 Answers

With regex module:

>>> s = "some english text ῍Ενθεσις τοῦ Ψαλτής and then english again"
>>> regex.sub(r'\p{Greek}+(\s+\p{Greek}+)*', r'\textgreek{\g<0>}', s)
'some english text \textgreek{῍Ενθεσις τοῦ Ψαλτής} and then english again'

This is based on given sample, not sure how want to deal with characters like non-greek punctuations.


If Greek_and_Coptic and Greek_Extended have all the characters you want to match, then you can manually construct the character range and thus use re module itself:

>>> s = "some english text ῍Ενθεσις τοῦ Ψαλτής and then english again"
>>> re.sub(r'[\u0370-\u03ff\u1f00-\u1fff]+(\s+[\u0370-\u03ff\u1f00-\u1fff]+)*', r'\textgreek{\g<0>}', s)
'some english text \textgreek{῍Ενθεσις τοῦ Ψαλτής} and then english again'
Related