我正在关注CSV
"name","isTrue","ID"
"ashok",True, 12
当我使用dictRead
读取它时,会附加单引号。
例如,输出为:
["name" : 'ashok', "isTrue":'True', "ID":'12']
我不希望它添加True
和12
值的引号,因为我的CSV中没有引号。我尝试使用常规文件读取,但再次分割行产生字符串列表。
任何人都可以帮我吗?
答案 0 :(得分:0)
一种方法是手动设置所需的类型。
<强>实施例强>
import csv
res = []
with open(filename, "r") as infile:
r = csv.DictReader(infile, delimiter=',')
for i in r:
i["isTrue"] = True if i["isTrue"] == 'True' else False
i["ID"] = int(i["ID"])
res.append(i)
print(res)
<强>输出:强>
[{'name': 'ashok', 'isTrue': True, 'ID': 12}]
答案 1 :(得分:0)
我不认为引用已添加到正在读取的数据。我相信引号只是表示读取内容的数据类型是字符串。我的其余部分假设您主要关心的是反序列化(即从CSV读取)内容的数据类型,而不是引号。
由于CSV是一个文本文件,因此反序列化过程不可能在没有任何上下文的情况下推断各列的数据类型。也就是说,如果您希望它能够在从CSV文件读取时执行此操作,您应该以某种方式将该反序列化函数传递给列上的数据类型信息。
另一种方法是对反序列化的字符串数据进行后处理。在阅读CSV的内容后,假设每列都有特定的数据类型,您可以对数据进行二次处理,将各列转换为正确的数据类型。
说,在阅读CSV后,您的数据存储在名为output
的词典列表中。
transformations = {'isTrue' : lambda x: x == 'True',
'ID' : lambda x: int(x)}
for row in output:
for key, val in row:
if key in transformations:
row[key] = transformations(val)
# output now contains the data in the desired form
请注意,您可以根据需要和正在处理的特定CSV文件展开transformations
字典。
除非你有一个特定的,预定的CSV文件,否则没有很多可靠的方法可以帮助你猜测任意表的列的数据类型。
一种方法可以使用正则表达式来检查列中看到的所有值,以找出该列的可能数据类型。然后,您可能在数据类型之间具有优先权,并相应地选择它们。
以下是我在上段所述内容的粗略实现。为简单起见,我们假设checkIfBool
,checkIfInt
,checkIfFloat
是将单个字符串作为输入并根据其正则表达式比较返回布尔值的方法。
data_types = ['float', 'int', 'bool']
data_type_transformations = {'float': lambda x: float(x),
'int': lambda x: int(x),
'bool': lambda x: x == 'True'}
column_list = output[0].keys()
column_possible_types_dict = {}
for column in column_list:
column_possible_types_dict[column] = set(data_types)
# Eliminate data types that are impossible for that column to have
for row in output:
for key, val in row:
if not checkIfFloat(val):
column_possible_types_dict.remove('float')
if not checkIfInt(val):
column_possible_types_dict.remove('int')
if not checkIfBool(val):
column_possible_types_dict.remove('bool')
# Decide which data type columns will have
# based on a precedence predetermined by you
column_types = []
for column in column_list:
if 'float' in column_possible_types_dict:
column_types.append('float')
elif 'int' in column_possible_types_dict:
column_types.append('int')
elif 'bool' in column_possible_types_dict:
column_types.append('bool')
else:
column_types.append('string')
# Conduct the transformations
for row in output:
for key, val in row:
if column_types[key] != 'string':
row[key] = data_type_transformations(val)
# output now contains the data in the desired form
答案 2 :(得分:0)
Python csv模块不添加任何引号。它只是假设一个csv文件包含 text 字段,它们用引号括起来并用分隔符分隔。它删除了可选引号,但永远不会将任何字符串转换为它的布尔值或数值:这取决于程序员。
要确保,只需执行以下代码:
row = {"name" : 'ashok', "isTrue":'True', "ID":'12'}
for k in row:
print(k, row[k])
您获得:
name ashok
isTrue True
ID 12
没有引号。
只有dict到string的默认转换会在文本值周围添加引号,以便将它们与数字或布尔值区分开来。