【问题标题】:Parse unicode to python data type将 unicode 解析为 python 数据类型
【发布时间】: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


【解决方案1】:

csv 阅读器会将所有值作为字符串返回。如果您需要将它们用作 int、float 等。您必须将它们从 string 转换为适当的类型。

对于相关的数字 csv 列,您可以像这样进行简单的字符串到 int/float 转换

my_int = int("21")
my_float = float("21.1")

【讨论】:

  • 这可行,但我希望我的代码通用意味着每列自动推断数据类型,因为我不知道哪一列 int 和 float。
  • 我看到的技术是尝试解析为浮动,如果失败则捕获异常。然后对 int 等做同样的事情。然后你的代码可以尝试每一个并坚持成功的那个。
【解决方案2】:

也许你对 Python 2 和 3 感到困惑。Str 在 Python 3 中是 unicode https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#unicode

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多