I'm creating a translation for a visual novel, and I can't translate the text with string formatting, does anyone know how to do this?
Code to translate:
$ gil_likes = "Teasing {0}, Basketball".format(Main)
The translation must be something like this:
old "Teasing Walter, Basketball" new "Дразнить Уолтера, Баскетбол"
I try to replace {0} with a specific name, but then the translation works only for that specific name, the problem is that the player can enter any name
Related
I want to write a program that shows the text in a cascading way Like This:
......
......
......
and my main problem is displaying the data.
I searched this site, and these are the pieces of code I wrote the program based on.
Print user input in “cascade” of characters?
i found the correct answer:
a="******"
for i in range(0,3):
print("\t"*(i+1),a)
If you are using code in cascade_name in Python 3 it won't work. Enclose print statement in brackets.
for index, value in enumerate("name"):
print(" "*index,value)
Why code like this wouldn't work?
replace "name" with input and you are good to go.
Instead of " " you can input as many spaces in cascading as you want.
I’m trying to adapt a script that currently contains the following segment:
# Initialize the output files
working_dir = os.getcwd()
output_path = "{}/{}".format(working_dir, "output_Prelim")
if not os.path.exists(output_path):
os.mkdir(output_path)
data_file = "{0}/RWA_2010_BUFFER_by_1.csv".format(output_path)
error_file = "{0}/failed_queries.txt".format(output_path)
In the statement that begins “data_file,” the parts of the file name “RWA” and “2010” refer to the country and year in which a particular survey was conducted.
I’m trying to adapt that segment so that the file name preserves the same general format, but allows the user to enter a different country code and year.
I can generate a string called “file_name” that looks right, using the following code:
print('Enter the country code')
cCode =input()
print('The country code is '+cCode)
print('Enter the survey year')
srvyYear =input()
print('The survey year is '+srvyYear)
file_name = r'"{0}/'+cCode+'_'+srvyYear+'_'+'BUFFER300_by_1.csv"'\
When I print “file_name,” I get
"{0}/BDI_2009_BUFFER300_by_1.csv"
That looks right, but am not sure what to do with it - in particular, how to get it understood as a file name rather than as a string. When I try to concatenate that string with the remainder of the statement that begins “data_file,” I get a syntax error.
Obviously I need to do a tutorial, but am not sure what to look for.
Many thanks, and apologies for the newbie question.
Not sure what your problem is exactly, but if you want to replace the {0} part with something else (e.g. the value in data_file), you can just do file_name.format(data_file).
Why not use join() method for string and os.path.join() for paht? e.g.
file_name = os.path.join(out_path, '_'.join([cCode, srvyYear, 'BUFFER300_by_1.csv']))
You can see its doc here, I believe that is what you needed, you'd better not concatenate string by yourself to construct path or filename. By the way, os.path.join() can construct filename without platform dependence, it will be a smart choice (especially for Windows).
I'm trying to load a specific key from a dictionary, with keys like "character 1", "translation 1", etc. (I'm working a a flashcard program for my chinese studies). First, I load the dictionary flawlessly from a .txt file with
f = codecs.open(('%s.txt' % list_name),'r','utf-8')
quiz_list = eval(f.read())
Then, I want the program to print the list in order, so that I would get something along the lines of
"1. ('character 1' value) ('pinyin 1' value) ('translation 1' value)"
The program registers how many entries the list has and calculates the amount of chinese words it has to show (with each word having its own character, transcription and translation and entry number). Now, I want to load the first chinese word from the list, with the 3 keys "character 1", "pinyin 1" and "translation 1".
The tried-and-tested way of retrieving values from a dictionary is through my_dictionary[key]. However, if I were to insert the name of a variable in the part between brackets, python would read the name of this variable as the name of a key, and not use the value of the variable. Is there a way of doing the latter the right way? I have, for example, tried the following (obviously to no avail) to load key "character 1" from the list:
i = 1
character_to_load = "character %s" % str(i)
print quiz_list[character_to_load]
Any hints are extremely appreciated!
A more general solution to this problem, instead of flattening the data structure into a dictionary keyed by strings, is to use a better data structure. For instance, if you have a lot of keys that look like "translation n" for numbers n, you'd be better off making translation a dictionary keyed by numbers. You might even want to make the lookup go the other way: you could have a Word object (or whatever) which has properties translation, pinyin and character, and then have a list of Words.
You should build this data structure properly, instead of evaling a file. That's basically never a good idea, because it's horribly fragile: you're forcing the text file to be pure Python, but not writing it as a module. Instead, you should iterate over the lines in the file and build up the data structure as you go.
If you tell me the current structure of your file I can give you an example as to how to parse it properly.
If I got you question right, I believe you might have some bug in the code, as this works fine:
>>> d = {'translation 1': 'dilligent', 'pinyin 1': 'ren4wei2', 'character 1': '\xe8\xaa\x8d\xe7\x88\xb2'}
>>> key = "translation %s" % 1
>>> d[key]
'dilligent'
Does it help?
What is the best way to approach writing a program in Python to translate English words and/or phrases into other languages?
AJAX Language API
This is an incredibly difficult problem -- language is very very very complicated. Think about all the things you'd have to do -- parse the phrase, work out what the words mean, translate them. That's probably not idiomatic so you'll need special cases for different syntaxes. Many, many special cases. You'll need to work out the syntax of the foreign language if it differs from English -- "the big green ball" goes to "the ball big green" in Spanish, for instance.
Don't reinvent the wheel. Google provide an API to their translation service, which has undoubtedly had many many clever people thinking really quite hard about it.
I think you should look into the Google Translate API. Here is a library implemented specifically for this purpose in python.
the simplest way to do this is to make a dictionary that matches one language's words to another language's words. However, this is extremely silly and would not take into account grammar at all and it would literally take a very long time to create a translator, especially if you plan to use it for multiple languages. If grammar is not important to you (for example, if you were creating your own language for a game or story that doesn't have grammar different from english) than you could get away with using dictionaries and simply having a function look for a requested match in the dictionary
# command : pip install mtranslate
from mtranslate import translate
>>> from mtranslate import translate
>>> translate("Tranalating to kannada language (my mother tongue) ", to_language = "kn")
'ಕನ್ನಡ ಭಾಷೆಗೆ ಅನುವಾದ (ನನ್ನ ಮಾತೃಭಾಷೆ)'
You can use Goslate Package for that
its very easy to use
example
import goslate
print(goslate.Goslate().translate('hello world', 'ar'))
now first argument is text you want to translate and second argument is in which language you want to translate.
i hope you will find the answer usefull
# Please install Microsoft translate using >> pip install translate
from translate import Translator
class clsTranslate():
def translateText(self, strString, strTolang):
self.strString = strString
self.strTolang = strTolang
translator = Translator(to_lang=self.strTolang)
translation = translator.translate(self.strString)
return (str(translation))
# Create a Class object and call the Translate function
# Pass the language as a parameter to the function, de: German zh: Chinese etc
objTrans=clsTranslate()
strTranslatedText= objTrans.translateText('Howare you', 'de')
print(strTranslatedText)
It's very very easy if you use deep-translator! Here's the source code(make sure to install deep-translator module):
from deep_translator import GoogleTranslator
import time
def start():
while True:
def translate():
line_to_translate = input('Which line/phrase/word you want to translate?\n')
to_lang = input('In which language you want to translate it?\n')
to_lang = to_lang.lower()
translation = GoogleTranslator(source='auto', target=to_lang).translate(text=line_to_translate)
return translation
time.sleep(1 sec)
esc = (input("Enter 'q' to exit and 'r' to restart.\n"))
while True:
if esc.lower() in {'q', 'r'}:
break
else:
print('Please enter a valid Option!!')
time.sleep(1)
esc = (input("Enter 'q' to exit and 'r' to restart.\n"))
if esc.lower() == 'q':
return
elif esc.lower() == 'r':
pass
start()
# command : pip install mtranslate
from mtranslate import translate
>>> from mtranslate import translate
>>> translate("Tranalating to kannada language (my mother tongue) ", to_language = "kn")
'ಕನ್ನಡ ಭಾಷೆಗೆ ಅನುವಾದ (ನನ್ನ ಮಾತೃಭಾಷೆ)'
I'm a beginner in Python. My problem is pretty simple. I have a string to be localized in a python application containing parameters :
print _('Hello dear user, your name is ') + params['first_name'] + ' ' + params['last_name'] + _(' and blah blah blah')
This actually does the job, but is not really what I would call a nice way to do it. Not to mention that some languages would, for example, require the last name to be displayed before the first name.
Is there a better way to do it ? I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying the string. But it seems not to be really more pleasant.
Thanks,
Pierre
I'd suggest
print 'Hello dear user, your name is %(first_name)s %(last_name)s' % params
Something like this should do the trick :
print _('Hello dear user, your name is %s %s and blah blah blah') % (params['first_name'], params['last_name'])
I would go with templates if I were you. That would let you have a separate template for each language. For example:
from string import Template
s_en = Template('Hello dear user, your name is $first_name $last_name and blah blah blah')
s_sco = Template('Hello, $first_name of the clan Mac$last_name...')
user = {'last_name': 'Duncan', 'first_name': 'Leod'}
print(s_en.substitute(user))
print(s_sco.substitute(user))
I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying them.
That's what I would do. Placeholders in the right places for each language versions should do the job.
One thing to mention that in some languages peoples names have to be modified dependent on where in a sentence and how they are used. You need to know each specific language to be able to do it correctly.
A possible solution: keep "in the middle of a sentence" cases to a minimum. Keep a localizable resource separated.
Instead of Hello dear user, your name is {{UserName}}
use User name: {{UserName}}