【发布时间】:2019-04-01 13:41:29
【问题描述】:
我正在使用 python 处理数据流。我在使用 python 中的内置 type() 推断数据类型时遇到了问题。
我尝试使用 utf-8 对该值进行编码并将 type() 应用于值,但它返回所有值的 str 类型,因为我需要实际的 python 数据类型,如 int、float。
我将字典作为输入,然后我正在解析我正在读取它的 csv 阅读器。
def parse_method(self, string_input):
# Strip out return characters and quote characters.
values = re.split(",",
re.sub('\r\n', '', re.sub(u'"', '', string_input)))
reader = csv.reader(values)
for csv_row in reader:
decoded_values=[x.decode('utf8') for x in csv_row]
for value in decoded_values:
print(value)
print(type(value))
row = dict( zip(('state', 'gender', 'year', 'name', 'number',
'created_date'),
values))
return row
Sample Output-
AK
<type 'list'>
F
<type 'list'>
1910
<type 'list'>
Lucy
<type 'list'>
6
<type 'list'>
11/28/2016
<type 'list'>
Expected output-
AK
<type 'str'>
F
<type 'str'>
1910
<type 'int'>
Lucy
<type 'str'>
6
<type 'int'>
11/28/2016
<type 'date'>
【问题讨论】:
-
请创建一个minimal reproducible example。如果通过正确的导入进行更正并从参数列表中删除
self,则此代码可以执行,但它不会返回与您的输出示例类似的任何内容。提供示例输入、运行的代码以及预期与实际输出。还要指定 Python 版本,因为csv模块在 Python 2 和 3 之间有很大不同。 -
另外,请查看
csv.DictReader。
标签: python unicode google-cloud-dataflow