Trish
Trish

Reputation: 11

Extract words surrounding a UNICODE word

This code works perfectly for this English sentence.

But when I try to do this with a sentence in Hindi language, it gives me error that word is not in the list.

This is my Hindi sentence:

प्रखर बुद्धि तेजस्वी बालक राजेन्द्र बाल्यावस्था में ही फारसी में शिक्षा ग्रहण करने लगा और उसके पश्चात प्राथमिक शिक्षा के लिए छपरा के जिला स्कूल |

I want to extract words adjacent to the word बालक.

Python code:

import re

sentence = 'The world is a small place, we should try to take care of it.'

words = re.findall(r'\w+', sentence)

index = words.index('place')

left = words[index - 3:index]

right = words[index + 1:index + 4]

Upvotes: 1

Views: 92

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You may do like this on python 3.

>>> import re
>>> s = 'प्रखर बुद्धि तेजस्वी बालक राजेन्द्र बाल्यावस्था में ही फारसी में शिक्षा ग्रहण करने लगा और उसके पश्चात प्राथमिक शिक्षा के लिए छपरा के जिला स्कूल |'
>>> re.findall(r'(\S+)\s+बालक\s+(\S+)', s)
[('तेजस्वी', 'राजेन्द्र')]

ie,.

>>> left, right = re.findall(r'(\S+)\s+बालक\s+(\S+)', s)[0]
>>> left
'तेजस्वी'
>>> right
'राजेन्द्र'
>>> 

Update:

To get two adjacent words.

>>> left, right = re.findall(r'(\S+\s+\S+)\s+बालक\s+(\S+\s+\S+)', s)[0]
>>> left
'बुद्धि तेजस्वी'
>>> right
'राजेन्द्र बाल्यावस्था'

Upvotes: 1

Related Questions