Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Consider, I have a Unicode encoded Malayalam text document say a.txt. I am putting away each word from that text document into a list. so that the list contains each word in the content.

example:

text="അവള്‍ പൊട്ടിക്കരഞ്ഞുകൊണ്ട് നൈല്‍ നദീതീരം മുഴുവന്‍ തന്‍റെ

      കാമുകന്‍റെ ശരീരഭാഗങ്ങള്‍ക്കായി അലഞ്ഞുനടന്നു. ഒരുപക്ഷെ, മറെറാരു

      പുരാണ-ഐതിഹ്യ കാവ്യങ്ങളിലും ഇത്ര ഹൃദയസ്പര്‍ശിയായ ഒരു തിരച്ചിലിന്‍റെ

      കഥ വിവരിക്കപ്പെട്ടിട്ടുണ്ടാവില്ല." 

In any case, the sentence boundaries are likewise attached to the final say regarding the sentence. like [അലഞ്ഞുനടന്നു.] I need to make it separate like [അലഞ്ഞുനടന്നു] [.] 

[വിവരിക്കപ്പെട്ടിട്ടുണ്ടാവില്ല] [.]

I'm also doing in this way

with codecs.open(r"C:\Users\cusat\Documents\Python Scripts\test document.txt",encoding="utf-8") as fpnr:

        text=fpnr.read() 

        text_of_sentences=segmentize(text)

        fpnr.close()  

    for sentence in text_of_sentences:

        if len(sentence) > 1:

            sentences.append(worder(sentence))

            #print sentences

    for sentence in sentences:

        #print sentence

        for word in sentence:

            #print word

            trimdwrds=trim(word)

            wordses.append(trimdwrds)

    for word in wordses:

           if len(word) >= 1:

               re.sub(r'([\u0900-\u097F]+)(\.)(\s*)', r'\1 \2', word) 

1 Answer

0 votes
by (26.4k points)

Look at the below code:

import re

words = [word for word in re.split('\s|(\.)', text) if word]

print(words)

['അവള്', 'പൊട്ടിക്കരഞ്ഞുകൊണ്ട്', 'നൈല്', 'നദീതീരം', 'മുഴുവന്', 'തന്റെ', 'കാമുകന്റെ', 'ശരീരഭാഗങ്ങള്ക്കായി', 'അലഞ്ഞുനടന്നു', '.', 'ഒരുപക്ഷെ,', 'മറെറാരു', 'പുരാണ-ഐതിഹ്യ', 'കാവ്യങ്ങളിലും', 'ഇത്ര', 'ഹൃദയസ്പര്ശിയായ', 'ഒരു', 'തിരച്ചിലിന്റെ', 'കഥ', 'വിവരിക്കപ്പെട്ടിട്ടുണ്ടാവില്ല', '.']

This actually splits your text string by either whitespace or . yet, it keeps the . since it is in a catching group in the regex. At that point, it filters through the vacant strings from the split.

Looking for a good python tutorial course? Join the python certification course and get certified.

For more details, do check out the below video tutorial...

Browse Categories

...