When i input a desire word which i want to translate i get a error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128). I write some comments to my lines. When the block "Write streams" begins to work - is print only first 2 streams even i input any word which include usuallatin simbols, for example: "White".
But, if i work in python 3 - it code works but i get following error. I parse my list named DATA to the list WORDS and i'd to write this content in a streams in 3 languages, but if i use
this:
Code: Select all
with open(filestream, mode='w', encoding='utf8') as stream:
stream.write(stream_content(dataitem))
i get incorrect content after reading. It looks like as:
Code: Select all
T:
r
R:
o
R:
o
J:
u
R:
o
B:
e
D:
o
T:
w
S:
t
S:
t
O:
p
W:
h
Y:
e
C:
a
B:
u
T:
r
C:
y
M:
o
P:
e
Д:
о
Д:
о
У:
ч
У:
с
П:
е
О:
п
О:
п
Д:
в
К:
р
К:
р
Р:
а
Б:
е
Ж:
ё
В:
о
В:
о
В:
о
В:
е
М:
о
П:
е
K:
r
Ú:
t
Ú:
t
E:
l
K:
ö
V:
e
E:
g
S:
z
V:
e
V:
e
F:
e
S:
á
G:
é
B:
u
T:
e
K:
e
M:
o
G:
y
Also i have a mistake, when i try return Word from function find_language. As i know if i put Word in some list and try to return it as list[0], because Word it is single right value, which i try to get through the loop
for it in range(len(Result)):
Code: Select all
<pre lang="Python"># -*- coding: utf-8 -*-
"""
Created on Sat Dec 31 03:33:00 2016
@author: SKY_SHY
"""
from codecs import open
def stream_content(data):
return '\n'.join(item[0] + ':\n ' + '\n '.join(item[1]) for item in data)
filename = "DATA_"
def translate():
Des_word = input("Enter a word you desire to translate:")# here i input a word, which i desire to translate in another language
print ('EN = 0', 'RU = 1', 'HU = 2')
Des_language = int(input("Select a language:"))# here i define a language, to which i desire to translate my word
return Des_word, Des_language
Des_word, Des_language = translate()
EN = [['Traffic sings',
['Junctions', 'Roundabout ahead', 'Bend ahead', 'Double bend ahead',
'Two-way traffic', 'Steep hill downwards', 'Steep hill upwards',
'Opening bridge ahead']],
['Road markings', ['White', 'Yellow']],
['Road users',
['Car-Drivers', 'Bus-Drivers', 'Truck-Drivers', 'Cycllists',
'Motorcyclists', 'Pedestrians']]]
RU = [['Дорожные знаки',
['Уступите дорогу', 'Пересечение с круговым движением', 'Опасный поворот',
'Опасные повороты', 'Двустороннее движение', 'Крутой спуск',
'Крутой подъём', 'Разводной мост']],
['Дорожная разметка', ['Белая', 'Жёлтая']],
['Участники движения',
['Водители легковых автомобилей', 'Водители автобусов',
'Водители грузовых автомобилей', 'Велосипедисты', 'Мотоциклисты',
'Пешеходы']]]
HU = [['Kresz táblák',
['Elsőbbségadás kötelező', 'Körforgalo', 'Veszélyes útkanyarulat',
'Egymás utáni veszélyes útkanyarulatok', 'Szembejövő forgalom', 'Veszélyes lejtő',
'Veszélyes emelkedő' 'Kompátkelés, vagy nyitható híd']],
['Útburkolati jelek', ['Fehér', 'Sárga']], ['Úthasználók',['Gépjárművezetők', 'Buszvezetők',
'Tehergépkocsi-vezetők', 'Kerékpárosok', 'Motorkerékpárosok', 'Gyalogosok']]]
# Here is my database of probable words, which i'm able to translate in this code:
DATA = [EN, RU, HU]
# I mark each language shortly
Labels = ['EN', 'RU', 'HU']
WORDS=[]
for k in range(len(DATA)):
g = [DATA[k][row][0] for row in range(len(DATA[k]))]
j=[]
for row in range(len(DATA[k])):
for i in range(len(DATA[k][row][1])):
j.append(DATA[k][row][1][i])
s =g+j
WORDS.append(s)
# write streams
for namestream, dataitem in zip(Labels, WORDS):
filestream = '{}:{}'.format(filename, namestream)
print (filestream, dataitem)
with open(filestream, mode='w', encoding='utf8') as stream:
stream.write(stream_content(dataitem))
# read streams
for namestream, dataitem in zip(Labels, WORDS):
filestream = '{}:{}'.format(filename, namestream)
with open(filestream, 'r', encoding='utf8') as stream:
sc = stream.read()
print(sc)
#Following function i write to check Is the DATA consist my word or not
def find_language(WORDS, Labels, Des_word):
RESULT=[]
for namestream, dataitem in zip(Labels, WORDS):
filestream = '{}:{}'.format(filename, namestream)
Result = []
with open(filestream, 'r', encoding='utf8') as stream:
sc = stream.read()
for it in sc.split():
Result.append(it)
Result=[str(t) for t in Result]
for it in range(len(Result)):
if Des_word == Result[it]:
Word=Result[it]# I check Does Des_word exist in this stream of file
print (Word)
RESULT.append(Word)
Your_language = filestream # Then i define the language
else:
continue
return RESULT[0], Your_language
Word, Your_language = find_language(WORDS, Labels, Des_word)
print (Word)
if Word is None:
if Des_language ==0:
print ("No such word!")
elif Des_language ==1:
print ("Нет такого слова!")
elif Des_language ==2:
print ("Nincs ilyen szo!")
else:
Translated_lang=[]
with open(Your_language, 'r', encoding='utf8') as stream:
sc = stream.readlines()
for inf in sc:
print (inf.rstrip('\n'))
Translated_lang.append(str(inf.rstrip('\n')))
'''Translated_lang=[str(h) for h in Translated_lang]# If i found my word in DATA then i read information from appropriate stream of the file and put all words in list'''
print (Translated_lang)
Translating_lang=[]
Str_of_trans_ing_lang = '{}:{}'.format(filename, Labels[Des_language])#Here i define name of stream which have words for translating my word
with open(Str_of_trans_ing_lang, 'r', encoding='utf8') as stream:
mc = stream.readlines()
for inf in mc:
Translating_lang.append(str(inf.rstrip('\n')))
'''Translating_lang=[str(sp) for sp in Translating_lang]# I put words from another stream, which include foreign words'''
print (Translating_lang)
DICT = dict(zip(Translated_lang, Translating_lang))
Trans_word = DICT[Des_word]# I find my word and translate it using this created dictionary.
print ("Your translate:" , Trans_word)