Search code examples
python-2.7nlpurdu

How can i clean urdu data corpus Python without nltk


I have a corpus of more that 10000 words in urdu. Now what i want is to clean my data. There appear a special uni coded data in my text like "!؟ـ،" whenever i use regular expressions it gives me error that your data is not in encoded form. Kindly provide me some help to clean my data. Thank you

Here is my sample data:

ظہیر

احمد

ماہرہ

خان

کی،

تصاویر،

نے

دائیں

اور

بائیں

والوں

کو

آسمانوں

پر

پہنچایا

،ہوا

ہے۔

دائیں؟

والے


Solution

  • I used your sample to find all words with ہ or ر

    Notice that I had to tell python that I am dealing with utf-8 data by using u in front of the regex string as well as the data string

    import re
    data = u"""
    ظہیر
    
    احمد
    
    ماہرہ
    
    خان
    
    .....
    """
    result = re.findall(u'[^\s\n]+[ہر][^\s\n]+',data,re.MULTILINE)
    print(result)
    

    The output was

    ['ظہیر', 'ماہرہ', 'تصاویر،', 'پہنچایا', '،ہوا']
    

    another example, removes all none alphabets except whitespace and makes sure only one whitespace separates the words

    result = re.sub(' +',' ',re.sub(u'[\W\s]',' ',data))
    print(result)
    

    the output is

     ظہیر احمد ماہرہ خان کی تصاویر نے دائیں اور بائیں والوں کو آسمانوں پر پہنچایا ہوا ہے دائیں والے 
    

    you can also use word tokanizer,

    import nltk
    result = nltk.tokenize.wordpunct_tokenize(data)
    print(result)
    

    the output will be

    ['ظہیر', 'احمد', 'ماہرہ'
     , 'خان', 'کی', '،', 'تصاویر'
     , '،', 'نے', 'دائیں', 'اور', 'بائیں', 'والوں'
     , 'کو', 'آسمانوں', 'پر', 'پہنچایا'
     , '،', 'ہوا', 'ہے', '۔', 'دائیں', '؟', 'والے']
    

    Edit ... for Python 2.7 you have to specify the encoding at the beginning of the code file as well as telling re that the regex is 'unicode' using re.UNICODE

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    import re
    
    data = u"""ظہیر
    
    احمد
    
    ماہرہ
    
    خان
    
    کی،
    
    .....
    
    """
    
    
    result = re.sub(ur'\s+',u' ',re.sub(ur'[\W\s]',ur' ',data,re.UNICODE),re.UNICODE)
    print(result)
    

    also note the use of ur'' to specify the string is a unicode regex string