如何让你的Python程序支持多语言
本文介绍如何通过Python标准库gettext
帮助你的程序支持多语言。
代码例子
import random
guessesTaken = 0
print(_("Hello! What's your name?"))
myName = input()
number = random.randint(1, 20)
print("Well, {}, I am thinking of a number between 1 and 20.".format(myName))
while guessesTaken < 6:
print("Take a guess.")
guess = input()
try:
guess = int(guess)
except ValueError:
print("You should give me a number.")
continue
if guess < number:
print("Your guess is too low.")
if guess > number:
print("You guess is too high.")
if guess == number:
break
if guess == number:
print("Good job, {}! You guessed my number in {} guesses!".format(
myName, guessesTaken))
if guess != number:
print("Nope. The number I was thinking of was {}.".format(number))
这是我们一个简单的猜数字游戏,我们执行看看过程。
$ python3 guess.py
Hello! What's your name?
Aidan
Well, Aidan, I am thinking of a number between 1 and 20.
Take a guess.
13
You guess is too high.
Take a guess.
2
Your guess is too low.
Take a guess.
12
You guess is too high.
Take a guess.
1
Your guess is too low.
Take a guess.
10
You guess is too high.
Take a guess.
9
Good job, Aidan! You guessed my number in 6 guesses!
程序是很漂亮了,可是老板突然要求你改成中文的,那么我们通常可能选择将字符串全部修改为相应中文,但是老板要让你自己针对不同用户不同语言就麻烦了。那有啥办法呢?Python标准库gettext
可以帮助我们。