Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中转换货币?_Python_List_Currency - Fatal编程技术网

如何在python中转换货币?

如何在python中转换货币?,python,list,currency,Python,List,Currency,我在做一个虚拟助理项目。我想让它告诉我其他货币的美元汇率。 我已经使用beautifulsoup编写了以下代码,它从给定的网站获取数据,解析数据并将结果打印在命令行中供我阅读。但这只是美元对PKR。我如何修改程序,使其接受任何货币,并告诉我该货币的兑换率? e、 g如果我问它“英国的美元汇率是多少?”,“阿联酋的英镑汇率是多少”,“美国的欧元汇率是多少?”它会返回转换率。下面给出了我所指的代码 import urllib.request from bs4 import BeautifulSoup

我在做一个虚拟助理项目。我想让它告诉我其他货币的美元汇率。 我已经使用beautifulsoup编写了以下代码,它从给定的网站获取数据,解析数据并将结果打印在命令行中供我阅读。但这只是美元对PKR。我如何修改程序,使其接受任何货币,并告诉我该货币的兑换率? e、 g如果我问它“英国的美元汇率是多少?”,“阿联酋的英镑汇率是多少”,“美国的欧元汇率是多少?”它会返回转换率。下面给出了我所指的代码

import urllib.request
from bs4 import BeautifulSoup

currency_page = 'http://www.xe.com/currencyconverter/convert/?Amount=1&From=USD&To=PKR'
currency = urllib.request.urlopen(currency_page)
currency_data = BeautifulSoup(currency, 'html.parser')

USD = currency_data.find('span', attrs={'class': 'uccResultUnit'})
USD_PKR = USD.text.strip() # strip() is used to remove starting and trailing
print(USD_PKR)
我试着编辑URL
http://www.xe.com/currencyconverter/convert/?Amount=1&From=USD&To=PKR
并将金额=1,从=USD,替换为=PKR


使用
Amount=custom\u Amount,From=any\u source\u curreny,To=any\u target\u currency
并将多个货币名称传递给变量,但我对此感到困惑。有人能建议怎么做吗?感谢您的帮助。感谢

一个简单的解决方案是根据用户输入动态构建url(您可以使用它)。例如:

#!/usr/bin/env python

from requests import get
from bs4 import BeautifulSoup
import sys

v1 = sys.argv[1]
v2 = sys.argv[2]
amount = sys.argv[3]

# check if the values passed are valid
# and construct the url like so:
currency_page = 'http://www......../convert/?Amount={}&From={}&To={}'.format(amount,v1,v2)

currency = get(currency_page).text
currency_data = BeautifulSoup(currency, 'html.parser')

USD = currency_data.find('span', attrs={'class': 'uccResultUnit'})
USD_PKR = USD.text.strip()
print(USD_PKR)

结果:

$ ./test.py EUR PKR 1                           
1 EUR = 125.790 PKR
另一个解决方案,如评论中所述,是使用

  • API或
  • 而是一个模块

  • 你为什么不使用API而不是抓取一个网页呢?外汇-结果将被发送到TTS引擎,它将为我说话。这就是为什么我放弃了它。API提供了这样的东西吗?它返回错误:urllib.error.HTTPError:HTTP error 400:BadRequest@Tauseef_Ahmed您是否将我帖子中的before
    /convert
    url部分替换为原始部分?由于典型的原因,我没有发布实际的url!我还尝试了代码,效果很好(我使用
    请求
    而不是
    urllib