Sort Non English Words in Text File Using Python

Code to sort your non English dictionary text file.

Maryam Bibi
1 min readAug 4, 2021
Photo by Edu Grande on Unsplash

Here, we are going to sort text file that contains words and we will use it later as our dictionary. For english language we can simply use:

list=['dog','cat','ant']
for element in sorted(list):
print(element)

But if want to sort other language words just sorted()will not work. Try code below and make changes according to your language requirements.

file=open('your_text_file_containing_words.txt', encoding='utf-8').read().split() #Your Language Alphabets Set(Here Urdu Alphabets Used)letters="آأابپتٹثجچحخدڈذرڑزژسشصضطظعغفقکگلمنںوؤہۂۃھءیئےۓ" #Assign Integer to Each Character 
d={i:letters.index(i) for i in letters}
#Sorted Function Based on First Character and Store Sorted Version in a List
sorted_list=sorted(file, key= lambda x: d[x[0]] if x[0] in d.keys() else float('inf'))
#Store List Elements in new Text File
sorted_file = open("New_Text_File_To Store_Sorted_Words.txt", "w")
for element in sorted_list:
sorted_file.write(element + "\n")
sorted_file.close()

In my case, text file containing words looks like this:

بجلی
کے
تار
بھی
آگ
کی
لپیٹ
میں
آنے
سے
شارٹ

After sorting:

آگ
آنے
بجلی
بھی
تار
سے
شارٹ
کے
کی
لپیٹ
میں

Give a clap if it worked for you👏🏼

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Maryam Bibi
Maryam Bibi

Written by Maryam Bibi

Self Learner and Evolving 🧘🏻‍♀️

No responses yet

Write a response