Mr.cysl
Mr.cysl

Reputation: 1614

How to sort a counter with Arabic in Python

Since Arabic starts at the right side, there will be bugs if I do the following:

cnt = {}
cnt["پ"] = 5 # right start char
cnt["t"] = 4 # left start char
import operator
sorted(cnt, key=operator.itemgetter(1), reverse=True)

Is there any way I could solve this problem?

Upvotes: 2

Views: 176

Answers (1)

user2357112
user2357112

Reputation: 281486

The error you're getting out of sorted has nothing to do with the Arabic. The error you're getting out of sorted is because you tried to sort cnt, but your key function is written as if it's sorting cnt.items(). If you add the items() call, sorted(cnt.items(), key=operator.itemgetter(1), reverse=True) will behave the same regardless of whether the keys of cnt use Arabic characters.

As for the display issues, those are due to Arabic. Getting mixed RTL and LTR text to display properly isn't easy, especially in a context like source code where you can't insert formatting characters without changing the meaning. I recommend not trying to use RTL characters in source code; you could move the Arabic to an external file. I would expect most Arabic in real programs to come from external input and localization files.

Upvotes: 1

Related Questions