Py学习  »  Python

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

Greenseed • 6 年前 • 2210 次点击  

编辑:

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'

是因为逗号吗?还是另有原因?(您可能还注意到,我添加了第二个“replace”,python不考虑这个问题?)

输入示例:

3596206198001,"4,43",A
3596206198001,"4,08",B
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40521
文章 [ 3 ]  |  最新文章 6 年前
Greenseed
Reply   •   1 楼
Greenseed    7 年前

我本不打算回答我自己的问题,但它可能会帮助一些其他初学者。 如果你被困在同一点上,就这样跟踪错误:

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

因为如前所述,如果你有大量的数据,你可能会有一些阻塞线或奇怪的输入你没有跟踪。

你可以纠正它,或者用这样的方法忽略错误:

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

还要注意你使用的是点而不是昏迷(例如1.6而不是1,6)

Daniel Roseman
Reply   •   2 楼
Daniel Roseman    7 年前

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

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

在冒号之后什么也得不到这一事实表明,实际上一开始就没有向float函数传递任何东西(即空字符串)。这几乎是肯定的,因为csv中的一行——可能是最后一行——在那一点上是空的。如果是这种情况,则应在尝试继续之前添加对空字符串的检查。

Matthieu Brucher
Reply   •   3 楼
Matthieu Brucher    7 年前

使用 . :

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