gpt4 book ai didi

python - 使用 type() 信息来转换存储为字符串的值

转载 作者:太空狗 更新时间:2023-10-30 02:34:36 24 4
gpt4 key购买 nike

在我的应用程序中,我生成了许多值(三列,类型为 int、str 和 datetime,请参见下面的示例),这些值作为逗号分隔的字符串存储在平面文件中。此外,我存储了一个包含值类型的文件(见下文)。现在,我如何使用此信息将我的值从平面文件转换为 Python 中的正确数据类型?有可能还是我需要做一些其他的事情?

数据文件:

#id,value,date
1,a,2011-09-13 15:00:00
2,b,2011-09-13 15:10:00
3,c,2011-09-13 15:20:00
4,d,2011-09-13 15:30:00

类型文件:

id,<type 'int'>
value,<type 'str'>
date,<type 'datetime.datetime'>

最佳答案

据我了解,您已经解析了文件,现在只需要获取正确的类型即可。所以假设id_ , type_value是包含文件中值的三个字符串。 (注意,type_ 应该包含 'int' — 例如 —,而不是 '<type 'int'>'

def convert(value, type_):
import importlib
try:
# Check if it's a builtin type
module = importlib.import_module('__builtin__')
cls = getattr(module, type_)
except AttributeError:
# if not, separate module and class
module, type_ = type_.rsplit(".", 1)
module = importlib.import_module(module)
cls = getattr(module, type_)
return cls(value)

然后你可以像这样使用它:

value = convert("5", "int")

不幸的是,对于 datetime 这不起作用,因为它不能简单地通过其字符串表示形式进行初始化。

关于python - 使用 type() 信息来转换存储为字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7402573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com