gpt4 book ai didi

python - 从 csv 文件中删除货币值(value)列中的引号?

转载 作者:行者123 更新时间:2023-12-01 05:51:28 25 4
gpt4 key购买 nike

要从 csv 文件的货币值(value)列中删除引号吗?

我的 CSV:

"   2102"|"LINDOMAR MARTINS DE FREITAS"|"RUA 02 NR.270"|"FORMOSA"|"98130860"|"TIMON"|"MA"|"ADMINISTRATIVO"|"FATURISTA"|"LINDOMAR"|"S"|20130102|20130102|20130102|115.00|"TDC"|"4"|"88792334"|""|""|""

我想要一个值为 115.00 的列不带引号。

L = []
reader = csv.reader(open(infile), csv.QUOTE_NONNUMERIC, delimiter='|', quotechar='"')

for row in reader:
L.append(tuple(row))

在 Python 列表 L 列中,值为 115.00 的值为 '115 .00 '。我认为该方法是 csv.header 在所有列上加上引号。

最佳答案

您可以只在适当的列上使用 float 。但请注意,由于舍入误差, float 值通常不用于货币值。 Python有专门的Decimal像这样输入,这比纯 float 有优势,值得注意的是:

... Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.

#!/usr/bin/env python

# consider: from decimal import Decimal
from pprint import pprint
import csv

if __name__ == '__main__':
L = []
reader = csv.reader(open("infile.csv"),
csv.QUOTE_NONNUMERIC, delimiter='|', quotechar='"')
for row in reader:
# consider: L.append( tuple( row[:14] + [Decimal(row[14])] + row[15:] ))
L.append( tuple( row[:14] + [float(row[14])] + row[15:] ))
pprint(L)

这会产生:

[(' 2102',
'LINDOMAR MARTINS DE FREITAS',
'RUA 02 NR.270',
'FORMOSA',
'98130860',
'TIMON',
'MA',
'ADMINISTRATIVO',
'FATURISTA',
'LINDOMAR',
'S',
'20130102',
'20130102',
'20130102',
115.0,
'TDC',
'4',
'88792334',
'',
'',
'')]

关于python - 从 csv 文件中删除货币值(value)列中的引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14131184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com