N
N
nurzhannogerbek2017-10-15 13:14:03
Django
nurzhannogerbek, 2017-10-15 13:14:03

How to correctly replace Latin characters with Cyrillic characters in the text?

Hello! Please help me figure it out.
In my django project, I have a form with a field where the user enters data and then creates a new post after submit. You need to enter in Russian. Faced the following problem.
The user, by mistake in the word "Country X", entered the letters "C" and "X" in Latin, and the rest of the letters in Cyrillic. Further, when the user searches and enters the word "Country" in Cyrillic, nothing is displayed. The result is displayed only when the user enters the words "Country", where C is written in Latin. I want to record everything in the database in Cyrillic at once. I'm trying to use the following code, but it didn't help. How to replace letters in words?

# Без этих импортов выводится ошибка: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# Латинские буквы 'ETOPAHKXCBMetopahkxcbm'
# Буквы кирилицы 'ЕТОРАНКХСВМеторанкхсвм'
WORDS = {
    "E": "Е",
    "T": "Т",
    "O": "О",
    "P": "Р",
    "A": "А",
    "H": "Н",
    "K": "К",
    "X": "Х",
    "C": "С",
    "B": "В",
    "M": "М",
    "e": "е",
    "t": "т",
    "o": "о",
    "p": "р",
    "a": "а",
    "h": "н",
    "k": "к",
    "x": "х",
    "c": "с",
    "b": "в",
    "m": "м"
}

***
def form_valid(self, form):
        title = form.cleaned_data['title'] # Поле формы
        for key in WORDS.keys():
            title = head.replace(key, str(WORDS[key])) # Замена не срабатывает
        form.save()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2017-10-15
@nurzhannogerbek

Manually mapping one letter to another to write. Wow.

eng = 'ETOPAHKXCBMetopahkxcbm'
rus = 'ЕТОРАНКХСВМеторанкхсвм'
mapping = str.maketrans(dict(zip(eng, rus)))
'tvoya stroka'.translate(mapping)  # 'тvоyа sтrока'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question