python - 浮动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
解决方案
ValueError 应该在错误之后显示错误的输入。它应该如下所示:
ValueError: could not convert string to float: '4,43'
冒号后什么都没有的事实表明,您实际上没有将任何内容(即空字符串)传递给 float 函数。这几乎可以肯定是因为您的 CSV 中的一行(可能是最后一行)此时是空的。如果是这种情况,您应该在尝试继续之前添加对空字符串的检查。
推荐阅读
- java - 为什么在进行数据更改之前调用 LiveData onChanged?
- apache - 是否可以在 Apache 输出过滤器中设置标题?
- php - 更改 Woocommerce 产品类别页面中的特定产品按钮文本
- c# - C# - 不能使用替换方法
- symfony - Symfony 在控制台命令中需要的参数不起作用
- assembly - 是否有任何解释语言暴露其字节码(或任何 IR)
- list - 这个 Prolog 代码是如何工作的 - 随机播放两个列表
- php - 在表中查找连续日期(MYSQL)
- android - 用户使用 SharedPreferences 保持登录 Android 应用程序不起作用
- android - Android Studio 3.1.4:在 Android Studio 项目中添加位图图像文件(不是应用程序图标)