ValueError: invalid literal for int() with base 10: '1000.00'

ValueError: invalid literal for int() with base 10: '1000.00'

我目前正在实施一个名为 BankAccount 的 class。它提供了设置余额、存款、取款和查看余额的功能。

现在我必须编写一个函数(称为 processAccounts()),它将文件名作为其参数。该文件的第一行将是一个数字,指定初始银行账户余额。接下来的行将指定一系列取款和存款,取款用 wW 标记,存款用 dD 标记。该函数必须读取文本文件,设置初始余额,然后根据文本文件的内容进行取款或存款。

这是我目前的情况:

class BankAccount:

    def set(self,balance=0):
        self.balance=balance        
    def deposit(self,amount):
        self.balance += amount
    def withdraw(self,amount):
        self.balance -= amount
    def get_balance(self):
        return self.balance
def processAccounts(fname):
    with open(fname,'r') as f:
    acct=[]
    for line in f:
        line=line.split()
        if line:
            line= [int(i) for i in line]
            acct.set(line)

文本文件:

1000.00
W 50.50
W 5.25
d 100.75
w 525.15
d 85.70

我目前正在尝试设置第一部分,该部分将读取第一行,然后调用 set() 函数来设置初始余额。

我得到的错误是:

ValueError: invalid literal for int() with base 10: '1000.00'

我是不是没有正确地处理这个问题,还是我没有正确地处理这个问题?

一般方法是正确的,但 int 显然是错误的,因为显然金额是用 "dollars.cents" 表示的。

float 似乎可以工作,但可能 不是 是正确的选择:处理货币金额反而是添加 decimal 模块的主要原因Python 标准库!使用 decimal,您将获得精确的计算,而不会出现四舍五入错误的风险,因为四舍五入会导致审计员对您束手无策。

所以我会这样做...:[=​​15=]

import decimal

class BankAccount:

    def set(self,balance=decimal.Decimal('0.00'):
        self.balance = balance  

# the rest of the class is fine.  Shd probably have an __init__ tho.
# also should keep an audit trail of deposit and withdrawals!

def processAccounts(fname):
    with open(fname,'r') as f:
        start_bal = decimal.Decimal(next(f).strip())
        ba = BankAccount()
        ba.set(start_bal)
        for line in f:
            fields = line.strip().split()
            if fields:
                if fields[0] in 'Ww':
                    ba.withdraw(decimal.Decimal(fields[1])
                elif fields[0] in 'Dd':
                    ba.deposit(decimal.Decimal(fields[1])
                else:
                    print('Ignoring line: {!r}'.format(line.strip()))
    return ba

首先,由于您使用的是金钱,正确的答案是使用 Alex Martelli 建议的 decimal class。

话虽如此,ValueError 的具体问题的答案可以用名为 fastnumbers(我是作者)的第 3 方模块来解决。它提供了一个名为 fast_forceint 的函数,该函数会将浮点数字符串(即 '1000.00')转换为 int.

>>> from fastnumbers import fast_forceint
>>> fast_forceint('1000.00')
1000
>>> isinstance(fast_forceint('1000.00'), int)
True

这个库是专门为减轻将字符串转换为数字类型的痛苦而设计的。

在不使用小数的情况下这样做 class(使用浮点数时不太准确),还包括一个构造函数:

class BankAccount():

def __init__(self, initialBalance = 0):
    self.accBalance = initialBalance 

def __repr__(self):
    return("BankAccount({})".format(self.accBalance))

def set(self, amount):
    self.accBalance = amount

def deposit(self, amount):
    self.accBalance += amount

def withdraw(self, amount):
    self.accBalance -= amount

def balance(self):
    return(self.accBalance)


def processAccount(filename ):
    with open(filename,'r') as f:
        b = BankAccount()
        startBal = f.readline().split()
        startBal = float(startBal[0])
        b.set(startBal)

        for line in f:
            fields = line.strip().split()
            if fields[0] in 'Ww':
            b.withdraw(float(fields[1]))
            elif fields[0] in 'Dd':
                b.deposit(float(fields[1]))

    return b