【问题标题】:error in my code help please python [closed]我的代码中的错误请帮助python [关闭]
【发布时间】:2023-03-26 17:18:01
【问题描述】:

这是我的代码,它不断出现相同的错误代码,我不确定为什么我会收到错误或它与我的代码有什么关系,任何信息都会有所帮助!我只是不太擅长处理错误

import urllib.request
import codecs
import matplotlib.pyplot as pyplot
import copy
from time import gmtime, strftime
from urllib.request import urlopen
def readInfo(filename):
    myFile = open(filename,'r')
    data=myFile.readlines()
    namelist=[i.split(' ', 1)[0] for i in data]
    balance = list()
    for item in data:
        name = item.split()[0]
        amount = float(item.split()[1])
        balance.append([name, amount])
    print("n",namelist,"c",balance)

    return (namelist, balance)
def fetch(url):
    def find_element(line, s_pattern, e_pattern, position=0):
        shift = len(s_pattern)
        start = line.find(s_pattern, position) + shift
        position = start
        end = line.find(e_pattern, position)
        return (line[start:end], position)
    html = urlopen(url)
    records = []
    i = 0
    for line in html.readlines():
        line = line.decode()
        if "<tr><td>" not in line:
             continue  # skip if line don't contain rows
        if "Currency" in line:
            continue  # skip header

        start = "<tr><td>"
        end = "</td>"
        element, start_pos = find_element(line, start, end)
        records.append([element])
        start = "<td>"
        values = []
        for x in range(2):
            element, start_pos = find_element(line, start, end, start_pos)
            values.append(element)
        records[i].append(values)
        i = i + 1
    print(records)
    return(records)

def findCurrencyValue(records, currency_name):
    d = dict(records)
    print(d[currency_name])
    return(d[currency_name])

def transaction(filename, namelist, orgBalance, url):
    exchange_info= fetch(url)
    #Read each line from transactions.txt
    myFile = open(filename,'r')
    data=myFile.readlines()
    #Check which company is conducting transactions
    bank = dict(orgBalance)
    for line in data:
        company,action,currency,ammount = line.split()
        do_something(company,action,currency,ammount,bank)
    #If BUY, then convert the amount of foreign currency to USD
    #and subtract the calculated amount
    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
def main():
    #get the namelist and original balance for all companies
    filename1 = "balance.txt"
    namelist, orgBalance = readInfo(filename1)
    #specifies the URL
    url = "https://www.cs.purdue.edu/homes/jind/exchangerate.html"
    #calculate the current balance for all companies
    balance = copy.deepcopy(orgBalance)
    filename2 = "transactions.txt"
    curBalance = transaction(filename2, namelist, balance, url)
    #output the value for the original balance for each company
    #this output should be a list of lists
    print("Original Balance of each company is: ", orgBalance)
    #output the value for the current balance for each company
    #this output should be a list of lists
    print("Current Balance of each company is: ", curBalance)
    #call your bar graph plotting function
    plotBarGraph(orgBalance, curBalance)
    #call your pie graph plotting function
    plotPieChart(curBalance)    
main()

当我运行代码时,我得到以下错误,我需要帮助修复

Traceback (most recent call last):
  File "C:\Users\noahd\Desktop\project3\project3-skeleton.py", line 134, in <module>
    main()
  File "C:\Users\noahd\Desktop\project3\project3-skeleton.py", line 123, in main
    curBalance = transaction(filename2, namelist, balance, url)
  File "C:\Users\noahd\Desktop\project3\project3-skeleton.py", line 63, in      transaction
    company,action,currency,ammount = line.split()
ValueError: too many values to unpack (expected 4)

【问题讨论】:

  • 该错误非常清楚地告诉您查看您的 line 变量,因为它在拆分时没有确切的 4 个东西。打印出来看看里面有什么。
  • 使用像pycharm这样的调试器来单步调试你的代码,或者在调试器中运行,当异常发生时它应该会自动中断
  • 我知道错误在哪里,我只是想看看是否有人可以帮我跟踪这个错误到实际问题,是否有人可以帮我解决它
  • 另外,如果您没有向我们展示输入,则真的很难帮助您解决基于输入的问题。
  • 这个问题的标题可能更有帮助。

标签: python error-handling


【解决方案1】:

似乎当你执行line.split()时,它返回的元素比需要的多,应该只有4个:company,action,currency,ammount。 不过,您可以尝试:

try:
    company,action,currency,ammount = line.split()
except:
    print "DEBUG: split:",line.split()

并检查错误在哪里

【讨论】:

  • 我在哪里把它放在代码中以便运行它
  • @NoahDukehart 你在上面声称你已经知道错误在哪里。
【解决方案2】:

试试:

transaction,company,action,currency,ammount,_ = line.split()

【讨论】:

    猜你喜欢
    • 2013-06-15
    • 2022-07-07
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多