【发布时间】:2018-10-29 15:39:00
【问题描述】:
编辑:
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 不会忽略您的替换调用,您是;您将它们分配给
columns,但随后忽略它并仅引用原始行属性。 -
用点代替逗号。将
4,43更改为4.43 -
您需要使用
locale库进行欧洲货币转换。见stackoverflow.com/a/40717213/719547。 -
您调用 'replace' 来获取列,但它不会更改行 [1] 内联。您必须在转换为浮动之前再次调用它:
prices = float(row[1].replace(',','.'))
标签: python