python - 如何在不使用语言环境模块的情况下获取国际货币符号?
问题描述
我需要获取 iso 货币符号,而不使用内置的 python 语言环境模块。
该locale
模块需要是安装在操作系统上的语言环境。我想在无服务器环境中运行我的代码,因此安装任何操作系统附加包都是一个障碍。
我需要的是相当于:
import locale
locale.setlocale(locale.LC_ALL, ('en_US', 'utf-8'))
currency_symbol = locale.localeconv()['int_curr_symbol']
解决方案
我使用Babel库解决了这个问题:
from babel import Locale
from babel.numbers import get_territory_currencies
from datetime import datetime
current_locale = Locale.parse('en_US')
current_date = datetime.utcnow().date
currency_symbol = get_territory_currencies(
current_locale.territory,
current_date,
current_date)[0]
此解决方案的一个限制是语言环境代码应具有区域。