python - 推断字符串中的数据类型

标签 python type-conversion

我想尝试推断字符串中数据的类型。

场景:
我有一个包含多行数据的 CSV 文件,我想将这些数据存储在数据库中。
我不想将所有字段存储为字符串。
由于 CSV 中的字段可能会发生变化,因此我无法对它们的类​​型做出任何假设。

示例(CSV 文件):

[Row 1 - column names] --> "name", "age" , "children"
[Row 2 - data row    ] --> "John", "45.5", "3"
...
[Row n - data row    ] --> ...

在这种情况下,通过查看行中的数据,我想推断出 name 是一列字符串,age 是一列 float ,并且children 是一列整数。

我的尝试:
最简单的方法是尝试转换,并在特定转换成功时决定类型。
我为此编写了一个方法,如下所示:

def deduceType(str):
    try:
        #first try to convert to int:
        int(str)
        return 0 #integer
    except ValueError:
        try:
            #not integer, try float:
            float(str)
            return 1 #float
        except ValueError:
            #not float, so deduct string
            return 2 #string

我的问题:
问题是,如果我希望能够推断出更多的数据类型( bool 值、长整型、无符号数字类型等),那么这种方法就会变得麻烦且不准确。

有没有更简洁、更高效、更严格的方法来做到这一点?

答案(编辑):
根据 Martijn Pieters 的回答,我正在这样做:

def deduceType(str):
    try:
        return type(ast.literal_eval(str))
    except ValueError:
        return type('') #string

最佳答案

使用ast.literal_eval()关于值(value);它会将其解释为 python 文字。如果失败,您将获得一个字符串。

>>> import ast
>>> ast.literal_eval("45.5")
45.5
>>> ast.literal_eval("3")
3
>>> ast.literal_eval("John")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

关于python - 推断字符串中的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13582142/

相关文章:

python - 无法导入咖啡

mysql - 解析MySql存储过程中的逗号(,)字符串

python - Pandas to_csv : suppress scientific notation in csv file when writing pandas to csv

C++ : convert uint64_t to unsigned char array

C# 从泛型值到字符串的转换问题

python - psycopg2 与 MySQLdb 反斜杠转义行为

python - 导入错误: No module named 'pkg_resources.extern.six.moves' ; 'pkg_resources.extern.six' is not a package

c - c中void*转int的解释

python - 在 Excel 中访问数据 - 来自 python 的路透社

python - 使用 python 从 Github 库中提取 CSV 文件