Reputation: 43
I have text with several irregular verbs. I want to find them in a text and translate, but I can't because some of them contain two words. And my method what I use to find them, find only first word in a verb.
text = “He gets. She gets away. She gets out. He gets past. He gets rid. He gives. She gives away. She gives up. He goes. He goes back. She goes on.”
vocabulary = {"gets":"получить","gets away":"уходить","gets out":"выбраться","gets past":"пройти мимо","gets rid":"избавиться","gives":"давать","gives away":"раздать","gives up":"сдаваться","goes":"идти","goes back":"возвращаться","goes on":"продолжать","She":"Она","He”:"Он"}
I want to get a result like that.
>>> Он получить. Она уходить. Она выбраться. Он пройти мимо. Он избавиться. Он давать. Она раздать. Она сдаваться. Он идти. Он возвращаться. Она продолжать.
How can I do this?
Upvotes: 2
Views: 100
Reputation: 107040
You can use re.sub
with an alternation pattern formed by joining the vocabularies from the longest to the shortest, and replace the match with the corresponding dict values:
import re
re.sub(r'\b(?:%s)\b' % '|'.join(sorted(vocabulary, key=len, reverse=True)), lambda m: vocabulary[m.group(0)], text)
This returns:
Он получить. Она уходить. Она выбраться. Он пройти мимо. Он избавиться. Он давать. Она раздать. Она сдаваться. Он идти. Он возвращаться. Она продолжать.
Upvotes: 1