user3057109
user3057109

Reputation: 51

matching Arabic word numbers with respective number in dictionary using Python

I am trying to match an Arabic number to a number, but it is not working. If it try the same method but without Arabic characters it works perfectly.

def Replace(text, wordDict):
    for key in wordDict:
        text = text.replace(key, wordDict[key])
    return text



singular = {
    "واحد" :"1",
    "اثنان" :"2",
    "ثلاتة" :"3"
}

s="ثلاثة"
s=Replace(s,singular)
print(s)

The output is ثلاثة although it should be 3, which means the replace operation was not performed. Any thoughts?

Upvotes: 1

Views: 214

Answers (1)

nyr1o
nyr1o

Reputation: 973

If you use special characters, you should use Unicode strings. The following code displays 3:

# -*- coding: utf-8 -*-

def num_replace(text, wordDict):
    for key in wordDict:
        text = text.replace(key, wordDict[key])
    return text

singular = {
    u"واحد": "1",
    u"اثنان" :"2",
    u"ثلاتة" :"3"
}

s = u"ثلاتة"
s = num_replace(s,singular)
print(s)

Read more about Unicode in Python.

Upvotes: 2

Related Questions