假设我有一个文本文件,如下所示:
3, 4.32, hi
7, 3.23, hello
当我读入这个文件时,所有条目都被视为字符串。有没有办法让它们(在我的示例中)自动转换为 int、float 和 string?
假设我有一个文本文件,如下所示:
3, 4.32, hi
7, 3.23, hello
当我读入这个文件时,所有条目都被视为字符串。有没有办法让它们(在我的示例中)自动转换为 int、float 和 string?
一种原始方法:
def guess(text):
for t in text.split(','):
for typ in (int, float, str):
try:
yield typ(t)
break
except ValueError as e:
pass
d = '3, 4.32, hi'
print list(guess(d))
# [3, 4.32, ' hi']
# [<type 'int'>, <type 'float'>, <type 'str'>]
但是 - 如果您知道类型应该是什么,那么这比像这样的暴力破解要好得多......
你可以利用这个ast
库来做一些工作,这可能会更灵活,对 try/except 机制的点击次数更少(并且读起来更容易,但确实需要在预处理输入方面做一些工作)
def guess2(text):
from ast import literal_eval
tokens = (t.strip() for t in text.split(','))
for token in tokens:
try:
token_value = literal_eval(token)
token_type = type(token_value)
yield token_value, token_type
except ValueError as e:
yield token, type(token)
如果您事先知道类型,您可以这样做:
import csv
type_funcs = [int, float, str]
with open('yourfile.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
typed_row = [func(val) for func, val in zip(type_funcs, row)]
如果所有文件中都有固定模式,则另当别论。
def update_types():
f = open("txtfile", "r")
reader = f.readlines()
for line in reader:
parts = line.split(',')
parts[0], parts[1] = int(parts[0]), float(parts[1])
for part in parts:
print type(part)
f.close()