Python - 要列出的文本,但不是字符串

时间:2017-11-24 02:33:01

标签: python list class text readline

我有一个包含类语句的文本文件:

Person('John Smith','1st Street','1987')
Patient('Steve White','2nd Street','1976','456 132 768 128','11/14/17','St. Johns','Warren','309C')
Employee('Roger Marks','3rd Street','1991','192837465','2011')
Doctor('Paul Warren','4th Street','1967','918213665','2007','250000','Cardiology','17')
Staff('Mike Clark','5th Street','1983','285018539','2009','Custodian','Sanatation','18', 'Full')

当我使用以下内容将它们输入列表时

infile = open('ClassData.txt', 'r')
line = infile.readline()
for line in infile:
    pObjects.append(line)

我用引号引用它们,例如:

pObjects = ["Person('John Smith','1st Street','1987')","Employee('Roger Marks','3rd Street','1991','192837465','2011')"]

如果没有引号,我可以更改哪些内容,以便将它们从列表中拉出并运行,例如,

pObjects = [Person('John Smith','1st Street','1987'),Employee('Roger Marks','3rd Street','1991','192837465','2011')]

1 个答案:

答案 0 :(得分:1)

您可以使用ast.literal_eval

import ast
pObjects = map(ast.literal_eval, pObjects)