字符串浮动python-不正确的格式?

时间:2018-10-29 15:39:01

标签: python

编辑:

with open("example.csv", "r", encoding="utf-8", errors="ignore") as new_data:
reader = csv.reader(new_data, delimiter=',', quotechar='"')
for row in reader:
    if row:
        if row[1] is not None:
            columns = (row[0], row[1].replace(",","."), row[2])
            ean = row[0]
            print(row[1])
            prices = float(row[1].replace(",","."))
            desc = row[2]
        #if prices is not None:
            result[ean].append((prices, desc)) 

但是我仍然感到奇怪:

C:\Users\User\AppData\Local\Programs\Python\Python37-32\python.exe 
C:/Users/User/AppData/Local/Programs/Python/Python37-32/get_min_price.py
Traceback (most recent call last):
4,43
File "C:/Users/User/AppData/Local/Programs/Python/Python37- 
32/get_min_price.py", line 17, in <module>
4,08
13,30
14,90
prices = float(row[1].replace(",","."))
9,31
5,02
4,19
ValueError: could not convert string to float: 
4,13
16,57
19,95
8,06
5,99
8,06

出于min函数的需要,我必须将字符串列表转换为float。但是我无法使它起作用:

result = defaultdict(list)

with open("example.csv", "r", encoding="utf-8", errors="ignore") as new_data:
reader = csv.reader(new_data, delimiter=',', quotechar='"')
for row in reader:
    if row:
        columns = (row[0], row[1].replace('"','').replace(',','.').strip(), row[2])
        ean = row[0]
        print (row[1])
        prices = float(row[1])
        desc = row[2]
        if prices is not None:
            result[ean].append((prices, desc)) #avoid getting an empty price as minimum value

输出:

4,43
Traceback (most recent call last):
File "C:/Users/User/AppData/Local/Programs/Python/Python37- 
32/get_min_price.py", line 16, in <module>
prices = float(row[1])
ValueError: could not convert string to float: '4,43'

是因为逗号吗?还是还有其他原因? (您可能还会注意到,我添加了Python并未考虑的第二个“替换”?)

输入示例:

3596206198001,"4,43",A
3596206198001,"4,08",B

3 个答案:

答案 0 :(得分:1)

使用.将字符串转换为正确的浮动格式:

prices = float(row[1].replace(",", "."))

答案 1 :(得分:1)

ValueError应该在错误之后显示错误的输入。 应该看起来像这样:

ValueError: could not convert string to float: '4,43'

冒号之后什么也没得到的事实表明,实际上,您实际上没有将任何内容(即空字符串)传递给float函数。这几乎可以肯定是因为CSV中的一行(可能是最后一行)当时是空的。如果是这种情况,您应该在尝试继续之前添加对空字符串的检查。

答案 2 :(得分:0)

我无意回答自己的问题,但这可能会对其他一些初学者有所帮助。 如果您停留在同一点,只需跟踪这样的错误:

 try:
price = float(price)
 except:
print(float)

由于如前所述,如果您有大量数据,则可能会遇到一些阻塞线或奇怪的输入,而您没有跟踪。

您可以通过以下方式纠正或忽略该错误:

 try:
price = float(price)
 except (TypeError, ValueError):
continue

还请注意,您使用的是点而不是逗号(例如1.6而不是1,6)