You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用forex_python.converter进行货币转换时EUR转USD汇率异常的修复咨询

问题

我编写了一个基于实时汇率的货币转换脚本,大部分场景运行正常,但在将EUR转换为USD时,汇率始终获取错误。例如,脚本显示1000 EUR仅值64 USD,而实际应约为950 USD——真实汇率为1.06,但forex-python库返回的是0.06。

给出的代码如下:

Module 1 (currency_rates.py)

from forex_python.converter import CurrencyRates


def exchange_rate(c1,c2, time):
    c = CurrencyRates()
    return c.get_rate(c1,c2, time)

Module 2

from currency_rates import exchange_rate
from datetime import datetime


# List of available currencies
list_of_currencies = ["USD", "EUR", "GBP", "ILS", "DKK", "CAD", "IDR", "BGN",
    "JPY", "HUF", "RON", "MYR", "SEK", "SGD", "HKD", "AUD", "CHF", "KRW", "CNY", "TRY", "HRK", "NZD", "THB", "LTL", "NOK", "RUB",
    "INR", "MXN", "CZK", "BRL", "PLN", "PHP", "ZAR"]


# Get user input for currency 1, amount and currency 2
c1 = input(f"""Which currency would you like to convert from?
 {list_of_currencies}
""")

if c1 not in list_of_currencies:
    print("Invalid answer.")

value_c1 = input("How much of that currency?
")

c2 = input(f"""Which currency would you like to convert to? 
 {list_of_currencies}
""")

if c2 not in list_of_currencies:
    print("Invalid answer.")


# Calculate result based on exchange rate
# Get current time
now = datetime.now()

rate = exchange_rate(c1,c2, now)

result = float(rate) * float(value_c1)


# Print result
print(f"{value_c1} {c1} are worth {result} {c2}.")

需要对汇率本身进行处理,但直接给小于1的汇率加1并非解决方案,因为部分真实汇率确实小于1。请问如何修复该问题?


解决方案

问题根源

forex-python的get_rate方法在处理部分货币对时,可能因数据源精度问题或单位换算错误返回异常值,比如你遇到的EUR→USD返回0.06,实际应为1.06,属于小数点位置错误(缺失整数位)。

修复方案

方案1:使用库内置的convert方法(最可靠)

forex-python的CurrencyRates类提供了convert方法,可直接完成货币转换,内部会自动处理汇率的正确性,避免单独获取汇率时的异常问题。

修改Module 1:

from forex_python.converter import CurrencyRates

def convert_currency(c1, c2, amount, time):
    c = CurrencyRates()
    return c.convert(c1, c2, amount, time)

修改Module 2的计算逻辑:

# 替换原有的rate和result计算代码
result = convert_currency(c1, c2, float(value_c1), now)

方案2:添加汇率验证与反向修正

如果坚持使用get_rate,可以在获取汇率后增加合理性校验,针对异常值尝试通过反向汇率取倒数修正:

from forex_python.converter import CurrencyRates

def exchange_rate(c1,c2, time):
    c = CurrencyRates()
    rate = c.get_rate(c1,c2, time)
    # 针对主流货币对设置合理范围
    major_pairs = [("EUR", "USD"), ("USD", "EUR"), ("GBP", "USD"), ("USD", "GBP")]
    if (c1, c2) in major_pairs:
        # 主流货币对汇率通常在0.5-2之间,超出则尝试反向修正
        if rate < 0.5 or rate > 2:
            reverse_rate = c.get_rate(c2, c1, time)
            rate = 1 / reverse_rate
    return rate

额外优化建议

  • 输入校验增强:当前代码在用户输入无效货币后仅打印提示,仍会继续执行后续逻辑,易引发报错。建议在输入无效时终止程序或重新获取输入。
  • 异常处理:添加try-except块捕获网络错误、汇率获取失败等异常,提升脚本稳定性。

内容的提问来源于stack exchange,提问作者ibdbpadw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:54:52