0

我正在使用 Python 3.7。我正在尝试将欧洲小数点,即逗号转换为小数点(即点)。

原始文件是 .csv 文件。

我的代码是:

#!/usr/bin/env python
import sys

for line in sys.stdin:
    # remove leading and trailing whitespace
    line = line.strip()
    # split data values into list
    data = line.split("\t")

    data = "{,:.}".format(data)
    print(data)

data = "{,:.}".format(data) 导致问题。

我得到的输出是:

Traceback (most recent call last):
  File "conPrep.py", line 10, in <module>
    data = "{,:.}".format(data)
KeyError: ','

任何帮助将不胜感激。

数据样本


#!/usr/bin/env python
import csv
from io import StringIO
import locale
import sys
from locale import atof

data = sys.stdin.readlines()

reader = csv.reader(data, delimiter='\t')
loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, 'german')
for row in reader:
    print([atof(x) for x in row])
locale.setlocale(locale.LC_ALL, loc) 

输出:

Traceback (most recent call last):
  File "conPrep.py", line 14, in <module>
    print([atof(x) for x in row])
  File "conPrep.py", line 14, in <listcomp>
    print([atof(x) for x in row])
  File "C:\Python37\lib\locale.py", line 326, in atof
    return func(delocalize(string))
ValueError: could not convert string to float: 'Data.Temperatura Media (C).Temperatura Minima (C).Temperatura Maxima (C).Precipitacao (mm).Final de Semana.Consumo de cerveja (litros)'
4

2 回答 2

0

最好使用localecsv内置模块python

请参阅下面的示例

import csv
from io import StringIO
import locale
from locale import atof

data = StringIO("""item1,item2,item3,item4
02/12/2015\t12,3\t1,3\t1.000,3\t1
02/12/2015\t32,3\t1,3\t1.000,3
02/12/2015\t2,3\t0,3\t1.000,3
02/12/2015\t1,3\t1.220,3\t3.000,3
""")

#Uncomment the below line to work with the csv file
#with open('test.csv') as data:
reader = csv.reader(data, delimiter='\t')
loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, 'german')
next(reader)
for row in reader:
    print([atof(x) if i>0 else x for i,x in enumerate(row)])
locale.setlocale(locale.LC_ALL, loc) 

将打印

[12.3, 1.3, 1000.3, 1.0]
[32.3, 1.3, 1000.3]
[2.3, 0.3, 1000.3]
[1.3, 1220.3, 3000.3]

编辑

data = StringIO...用行替换with open('filename.csv') as data:

于 2019-12-03T12:01:03.983 回答
0

尝试使用replace在字符串类上定义的函数

#!/usr/bin/env python
import sys

for line in sys.stdin:
    # remove leading and trailing whitespace
    line = line.strip()
    # split data values into list
    data = line.split("\t")
    data = data.replace(',', '.')
    print(data)
于 2019-12-03T11:50:44.780 回答