The Wayback Machine - https://web.archive.org/web/20240909201508/https://www.geeksforgeeks.org/transliterating-non-ascii-characters-with-python/
Open In App

Transliterating non-ASCII characters with Python

Last Updated : 08 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Transliteration is a process of writing the word of one language using similarly pronounced alphabets in other languages. It deals with the pronunciation of words in other languages.  Similarly, in computer language, the computer can handle ASCII characters but has problems with non-ASCII characters. There are some times when we are unable to skip non-ASCII characters as it can lead to loss of information.  There should be a way to read non-ASCII characters and express them by text in ASCII characters. 

Approach 1:

This approach is related to the inbuilt library unidecode. This library helps Transliterating non-ASCII characters in Python. It provides an unidecode() method that takes Unicode data and tries to represent it in ASCII.  This method automatically determines scripting language and transliterates it accordingly. It accepts unicode string values and returns a transliteration in string format.

Steps:

  • Import unidecode library
  • Call unidecode() method with input text

Example:

Python3




# Import unidecode module from unidecode
from unidecode import unidecode
 
# Get transliteration for following
# non-ASCII text (Unicode string)
print(unidecode(u'ko\u017eu\u0161\u010dek'))
 
# Get transliteration for following
# non-ASCII text (Devanagari)
print(unidecode("āΆāĪŠ āĪĻāĨ€āΚāĨ‡ āĪ…āĪŠāĪĻāĨ€ āĪ­āĪūāĪ·āĪū āĪ”āΰ ā·āĪĻāĪŠāĨāΟ āΉāĪŠāĪ•āΰāĪĢ āΚāĨāĪĻāĨ‡āĪ‚ āĪ”āΰ āĪēāĪŋāĪ–āĪĻāĪū āΆāΰāĪ‚āĪ­ āĪ•āΰāĨ‡āĪ‚"))
 
# Get transliteration for following
# non-ASCII text (Chinese)
print(unidecode("č°Ēč°Ēä― "))
 
# Get transliteration for following
# non-ASCII text (Japanese)
print(unidecode("ありがãĻう。"))
 
# Get transliteration for following
# non-ASCII text (Russian)
print(unidecode("҃ÐŧŅ‹ÐąÐ°Ņ‚ŅŒŅŅ ВÐŧаÐīÐļОÐļŅ€ ÐŸŅƒŅ‚ÐļÐ―"))


Output:

kozuscek
aap niice apnii bhaassaa aur inputt upkrnn cuneN aur likhnaa aarNbh kreN
Xie Xie Ni
arigatou.
ulybat'sia Vladimir Putin

Approach 2: 

This approach deals with building a structure that will help in transliteration. In this, Unicode values of non-ASCII characters are labeled with related ASCII values from here provides a list of scripts. Unicode’s value for letters in each script is provided therewith representable ASCII character. Wikipedia also has a collection of Unicode values and respective transliteration.

Steps:

  • Create Dictionary having Unicode values as keys and ASCII representation as values
  • Transliterate each letter in the text using that dictionary.

For example, if we want transliteration of the Russian language, we will take all letters in Cyrillic script as Russian uses Cyrillic. Then for each letter, its Unicode value and ASCII representation are used to create a dictionary. And, then this dictionary is used to transliterate given text.

For example, some letters of Devanagari script are taken and a dictionary is created. Further, it is used on small text for transliteration.

Example:

Python




# Create devanagari transliteration dictionary
devanagari_translit_dict = {
    '\u0905': 'A', '\u0906': 'AA', '\u0907': 'I', '\u0908': 'II',
    '\u0909': 'U', '\u090A': 'UU', '\u090F': 'E', '\u0910': 'AI',
    '\u0913': 'O', '\u0914': 'AU', '\u0915': 'K', '\u0916': 'KH',
    '\u0917': 'G', '\u0918': 'GH', '\u0919': 'NG', '\u091A': 'C',
    '\u091B': 'CH', '\u091C': 'J', '\u091D': 'JH', '\u091E': 'NY',
    '\u091F': 'TT', '\u0920': 'TTH', '\u0921': 'DD', '\u0922': 'DDH',
    '\u0923': 'NN', '\u0924': 'T', '\u0925': 'TH', '\u0926': 'D',
    '\u0927': 'DH', '\u0928': 'N', '\u092A': 'P', '\u092B': 'PH',
    '\u092C': 'B', '\u092D': 'BH', '\u092E': 'M', '\u092F': 'Y',
    '\u0930': 'R', '\u0932': 'L', '\u0933': 'LL', '\u0935': 'V',
    '\u0936': 'SH', '\u0937': 'SS', '\u0938': 'S', '\u0939': 'H',
    '\u093E': 'AA', '\u093F': 'I', '\u0940': 'II', '\u0941': 'U',
    '\u0942': 'UU', '\u0947': 'E', '\u0948': 'AI', '\u094B': 'O',
    '\u094C': 'AU', '\u094D': '', '\u0902': 'n'}
 
# Define function transliterating text
def transliterate(text, translit_dict):
    new_word = ''
    for letter in text:
        new_letter = ''
        if letter in translit_dict:
            new_letter = translit_dict[letter]
        else:
            new_letter = letter
        new_word += new_letter
    return new_word
 
# Input text in devanagari
text = "āΆāĪŠ āĪĻāĨ€āΚāĨ‡ āĪ…āĪŠāĪĻāĨ€ āĪ­āĪūāĪ·āĪū āĪ”āΰ ā·āĪĻāĪŠāĨāΟ āΉāĪŠāĪ•āΰāĪĢ āΚāĨāĪĻāĨ‡āĪ‚ āĪ”āΰ āĪēāĪŋāĪ–āĪĻāĪū āΆāΰāĪ‚āĪ­ āĪ•āΰāĨ‡āĪ‚"
 
# Obtain Transliterated text for given input text
transliterated_text = transliterate(text, devanagari_translit_dict)
print(transliterated_text)


Output:

AAP NIICE APNII BHAASSAA AUR INPUTT UPKRNN CUNEn AUR LIKHNAA AARnBH KREn


Similar Reads

Check if a string contains a non-ASCII value in Julia - ascii() Method
The ascii() is an inbuilt function in Julia which is used to convert a specified string to a String type and also check the presence of ASCII data. If the non-ASCII byte is present, throw an ArgumentError indicating the position of the first non-ASCII byte. Syntax: ascii(s::AbstractString) Parameters:s::AbstractString: Specified stringReturns: It r
1 min read
Python Encode Unicode and non-ASCII characters into JSON
This article will provide a comprehensive guide on how to work with Unicode and non-ASCII characters in Python when generating and parsing JSON data. We will look at the different ways to handle Unicode and non-ASCII characters in JSON. By the end of this article, you should have a good understanding of how to work with Unicode and non-ASCII charac
5 min read
How to remove all Non-ASCII characters from the string using JavaScript ?
In this article, we are given a string containing some non-ASCII characters and the task is to remove all non-ASCII characters from the given string. Approaches to remove all Non-ASCII Characters from String: Table of Content Using ASCII values in JavaScript regExUsing Unicode in JavaScript regExUsing ASCII values with the Array filter methodApproa
3 min read
What is ASCII - A Complete Guide to Generating ASCII Code
The American Standard Code for Information Interchange, or ASCII, is a character encoding standard that has been a foundational element in computing for decades. It plays a crucial role in representing text and control characters in digital form. Historical BackgroundASCII has a rich history, dating back to its development in the early 1960s. Origi
13 min read
Substring with maximum ASCII sum when some ASCII values are redefined
Given a string W, and two arrays X[] and B[] of size N each where the ASCII value of character X[i] is redefined to B[i]. Find the substring with the maximum sum of the ASCII (American Standard Code for Information Interchange) value of the characters. Note: Uppercase & lowercase both will be present in the string W. Input: W = "abcde", N = 1,
9 min read
ASCII NULL, ASCII 0 ('0') and Numeric literal 0
The ASCII (American Standard Code for Information Interchange) NULL and zero are represented as 0x00 and 0x30 respectively. An ASCII NULL character serves as a sentinel character of strings in C/C++. When the programmer uses '0' in his code, it will be represented as 0x30 in hex form. What will be filled in the binary integer representation in the
3 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 min read
Converting an Integer to Ascii Characters in Python
In Python, working with integers and characters is a common task, and there are various methods to convert an integer to ASCII characters. ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents text in computers. In this article, we will explore some simple and commonly used methods for convertin
3 min read
Longest string in non-decreasing order of ASCII code and in arithmetic progression
Given a non-empty string S of uppercase alphabets of length L the task is to find the longest string from the given string with characters arranged in descending order of their ASCII code and in arithmetic progression such that the common difference should be as low as possible and the characters of the string to be of higher ASCII value. Note: The
10 min read
Increase the ASCII value of characters of the string by the given values
Content Removed
1 min read
Queries to calculate sum of squares of ASCII values of characters of a substring with updates
Given a string S of length N and a 2D array of strings Q[][] consisting of M queries of the following type: Query("U", "I", "X"): Update the character at index I with the character X.Query("S", "L", "R"): Print the sum of the squares of the position of the characters in the substring {S[L], ...., S[R]} according to the English alphabets. Examples:
15+ min read
Remove k characters in a String such that ASCII sum is minimum
Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2 characters from the string "ABbc" to minimize the
7 min read
Maximize ascii sum removing K characters in String
Given a string s and an integer K, the task is to remove K characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is maximized. Examples: Input: s = "word", K = 2Output: 233Explanation: We need to remove exactly 2 characters from the string "word" to maximize the
9 min read
Sort the string as per ASCII values of the characters
Given a string S of size N, the task is to sort the string based on its ASCII values. Examples: Input: S = "Geeks7"Output: 7GeeksExplanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets. Input: S = "GeeksForGeeks"Output: FGGeeeekkorss Approach: The idea to solve this problem is to maintain an
6 min read
Sort an array of strings in increasing order of sum of ASCII values of characters
Given an array arr[] consisting of N strings, the task is to sort the strings in increasing order of the sum of the ASCII (American Standard Code for Information Interchange) value of their characters. Examples: Input: arr[] = {"for", "geeks", "app", "best"}Output: app for best geeksExplanation:Sum of ASCII values of characters of each string is: {
7 min read
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number
Given an array arr[] of size N containing strings, the task is to count the number of strings having the sum of ASCII (American Standard Code for Information Interchange) values of characters equal to an Armstrong Number number or a Prime Number. Examples: Input: arr[] = {"hello", "nace"}Output:Number of Armstrong Strings are: 1Number of Prime Stri
12 min read
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1. Examples: Input: S = "acbbebcg"Output: 5Explanation: The longest subsequence of required type is "cbbbc", whose length is 5.Th
6 min read
How to validate if input in input field has ASCII characters using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: Ãą). We can als
4 min read
How to set ASCII Characters in MaskedTextBox in C#?
In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask that differentiates between proper and improper user input. In MaskedTextBox control, you are allowed to insert ASCII or non-ASCII(arbitrary Unicode characters) characters in the Mas
3 min read
Count pairs of characters in a string whose ASCII value difference is K
Given string str of lower case alphabets and a non-negative integer K. The task is to find the number of pairs of characters in the given string whose ASCII value difference is exactly K. Examples: Input: str = "abcdab", K = 0 Output: 2 (a, a) and (b, b) are the only valid pairs.Input: str = "geeksforgeeks", K = 1 Output: 8 (e, f), (e, f), (f, e),
7 min read
Find the sum of the ascii values of characters which are present at prime positions
Given string str of size N, the task is to find the sum of all ASCII values of the characters that are present at prime positions. Examples: Input: str = "abcdef" Output: 298 'b', 'c' and 'e' are the only characters which are at prime positions i.e. 2, 3 and 5 respectively. And sum of their ASCII values is 298.Input: str = "geeksforgeeks" Output: 6
8 min read
Count characters in a string whose ASCII values are prime
Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime. Examples: Input: S = "geeksforgeeks" Output : 3 'g', 'e' and 'k' are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively. Input: S = "abcdefghijklmnopqrstuvwxyz" Output: 6 Approach: The idea is to gen
6 min read
Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
Given a string and a number k, the task is to find the number of substrings of length k whose sum of the ASCII value of characters is divisible by k. Examples: Input : str = "bcgabc", k = 3 Output : 2 Substring "bcg" has sum of ASCII values 300 and "abc" has sum of ASCII values 294 which are divisible by 3. Input : str = "adkf", k = 3 Output : 1 Br
8 min read
Convert all lowercase characters to uppercase whose ASCII value is co-prime with k
Given an integer 'k' and a string 'str' consisting of characters from English alphabets. The task is to convert all lower case character to uppercase whose ASCII value is co-prime with k. Examples: Input: str = "geeksforgeeks", k = 4 Output: GEEKSfOrGEEKS 'f' and 'r' are the only characters whose ASCII values aren't co-prime with 4. Input: str = "A
6 min read
Sub-strings having exactly k characters that have ASCII value greater than p
Given a string 'str', two integers 'k' and 'p'. The task is to count all the sub-strings of 'str' having exactly 'k' characters that have ASCII values greater than 'p'. Examples: Input: str = "abcd", k=2, p=98 Output: 3 Only the characters 'c' and 'd' have ASCII values greater than 98, And, the sub-strings containing them are "abcd", "bcd" and "cd"
7 min read
Average of ASCII values of characters of a given string
Given a string, the task is to find the average of ASCII values of characters in the string. Examples: Input: str = "for"Output: 109'f'= 102, 'o' = 111, 'r' = 114(102 + 111 + 114)/3 = 109 Input: str = "geeks" Output: 105 Source: Microsoft Internship Experience Approach: Start iterating through characters of the string and add their ASCII value to a
5 min read
Program to find the largest and smallest ASCII valued characters in a string
Given a string of lowercase and uppercase characters, your task is to find the largest and smallest alphabet (according to ASCII values) in the string. Note that in ASCII, all capital letters come before all small letters. Examples : Input : sample stringOutput : Largest = t, Smallest = aInput : GeeksOutput : Largest = s, Smallest = GExplanation: A
6 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
Article Tags :
Practice Tags :