Regular Expression to accept all Thai characters and English letters in python

后端 未结 3 1169
野的像风
野的像风 2020-12-30 12:23

I need to vectorize text documents in Thai (e.g Bag of Words, doc2vec).

First I want to go over each document, omitting everything except the Thai characters and En

3条回答
  •  渐次进展
    2020-12-30 12:48

    I'll be using some lists to do what I need.

    First, let's create the pattern :

    pattern = re.compile(r"[^\u0E00-\u0E7Fa-zA-Z' ]|^'|'$|''")
    

    I'll use a string named test_string, containing your example :

    test_string="ทรูวิชั่นส์ ประกาศถ่ายทอดสดศึกฟุตบอล พรีเมียร์ ลีก อังกฤษ ครบทุกนัดเป็นเวลา 3 ปี ตั้งแต่ฤดูกาล 2016/2017 - 2018/2019 พร้อมด้วยอีก 5 ลีกดัง อาทิ ลา ลีกา สเปน, กัลโช เซเรีย เอ อิตาลี และลีกเอิง ฝรั่งเศส ภายใต้แพ็กเกจสุดคุ้ม ทั้งผ่านมือถือ และโทรทัศน์ some, English words here! abc123"
    

    First, let's get the characters to remove, in a list :

    char_to_remove = re.findall(pattern, test_string)
    

    Then, let's create a list made of the character from our original string, without these characters :

    list_with_char_removed = [char for char in test_string if not char in char_to_remove]
    

    We transform this list into a string, and we're done.

    result_string = ''.join(list_with_char_removed)
    

    Result is :

    'ทรูวิชั่นส์ ประกาศถ่ายทอดสดศึกฟุตบอล พรีเมียร์ ลีก อังกฤษ ครบทุกนัดเป็นเวลา ปี ตั้งแต่ฤดูกาล พร้อมด้วยอีก ลีกดัง อาทิ ลา ลีกา สเปน กัลโช เซเรีย เอ อิตาลี และลีกเอิง ฝรั่งเศส ภายใต้แพ็กเกจสุดคุ้ม ทั้งผ่านมือถือ และโทรทัศน์ some English words here abc'

    If you have any cleaner way to do any of the steps/any questions, do not hesitate !

提交回复
热议问题