阅读文件和相关信息

时间:2015-11-04 00:01:35

标签: python list text

我获得以下骨架

#This function helps calculate each transactions and return the final balance
#PARAMETERS:
#filename: the file going to be read, e.g. "transactions.txt", type: string
#namelist: a list containing all company names, type: list
#orgBalance: stores original balance for each company, type: nested list
#url: the url you are trying to fetch, type: string
#RETURN: current balance information (after all transactions), type: nested list
def transaction(filename, namelist, orgBalance, url):

     #Call fetch(url) to get currency exchange information
     exchange_info= fetch(url)
     #Read each line from transactions.txt
     myFile = open(filename,'r')
     data=myFile.readlines()
     #Check which company is conducting transactions

     #If BUY, then convert the amount of foreign currency to USD
     #and subtract the calculated amount 

     #If SELL, then convert the amount of foreign currency to USD
     #and add the calculated amount 

     #Return current balance list
     #your list should look like 
     #[['Acer', 481242.74], ['Beko', 966071.86], ...]

我的数据清单如下:

transaction.txt

Gerdau BUY Brazilian Real: 17454
Gerdau SELL Botswana Pula: 31162
Acer BUY Danish Krone: 61376
Equifax BUY Icelandic Krona: 41983
Acer BUY Sri Lankan Rupee: 91659
Datsun SELL Trinidadian Dollar: 71248
Haribo BUY Indonesian Rupiah: 41548
Datsun SELL Saudi Arabian Riyal: 71627
namelist=['Acer', 'Beko', 'Cemex', 'Datsun', 'Equifax', 'Gerdau', 'Haribo']
orgBalance=[['Acer', 481242.74], ['Beko', 966071.86], ['Cemex', 187242.16], ['Datsun', 748502.91], ['Equifax', 146517.59], ['Gerdau', 898579.89], ['Haribo', 265333.85]]
and the url=https://www.cs.purdue.edu/homes/jind/exchangerate.html

我只是想知道是否有人可以引导我完成这个,我得到前几个部分,但是一旦我得到第三个评论,我就输了。我不确定如何解决哪些公司正在购买或出售

1 个答案:

答案 0 :(得分:0)

bank = dict(orgBalance)
for line in data:
    company,action,currency,ammount = line.split()
    do_something(company,action,currency,ammount,bank)

那么您需要编写一个实际将货币转换为usd的函数do_something,然后从公司银行账户中添加或减去

def find_currency_rate(currency):
    # locate the curency name in the text body and find the last <td></td> value in that row...
    return float(last_td_cell_of_row)

def convert_to_usd(currency,amount):
    currency_rate = find_currency_rate(currency)
    return amount*currency_rate

def do_something(company_name,action,currency_code,amount,bank):
    amount_in_usd = convert_to_usd(currency_code,amount)
    if action == "BUY":
       bank[company_name] = bank[company_name] - amount_in_usd
    else: # else we sell and add the funds to our bank
       bank[company_name] = bank[company_name] + amount_in_usd