首页 > 解决方案 > 浮动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 函数的需要,我必须将字符串列表转换为浮点数。但是我不能让它工作:

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

标签: python

解决方案


ValueError 应该在错误之后显示错误的输入。它应该如下所示:

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

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


推荐阅读