如何将文本格式列表转换为python列表

时间:2013-07-22 18:23:18

标签: python parsing

我从配置文件中获取各种数据类型并将它们添加到字典中。但我的列表有问题。我想在文本中添加一行:alist = [1,2,3,4,5,6,7]并转换为整数列表。但我得到了

['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7'].  

我该如何解决这个问题?

这是config.txt:

firstname="Joe"
lastname="Bloggs"
employeeId=715
type="ios"
push-token="12345"
time-stamp="Mon, 22 Jul 2013 18:45:58 GMT"
api-version="1" 
phone="1010"
level=7
mylist=[1,2,3,4,5,6,7]

这是我要解析的代码:

mapper = {}

def massage_type(s):
    if s.startswith('"'):
        return s[1:-1]
    elif s.startswith('['):
        return list(s[1:-1])   #in this case get 'mylist': ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7']
    elif s.startswith('{'):
        return "object"   #todo
    else:
        return int(s)



doc = open('config.txt')
for line in doc:
    line = line.strip()
    tokens = line.split('=')
    if len(tokens) == 2:
        formatted = massage_type(tokens[1])
        mapper[tokens[0]] = formatted

    #check integer list
    mapper["properlist"] = [1,2,3,4,5,6,7]  #this one works

print mapper

这是我的打印输出:

{'time-stamp': 'Mon, 22 Jul 2013 18:45:58 GMT', 'mylist': ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7'], 'employeeId': 715, 'firstname': 'Joe', 'level': 7, 'properlist': [1, 2, 3, 4, 5, 6, 7], 'lastname': 'Bloggs', 'phone': '1010', 'push-token': '12345', 'api-version': '1', 'type': 'ios'}

更新

感谢您的反馈。我意识到我也可以获得异构列表,因此将列表部分更改为:

elif s.startswith('['):
    #check element type
    elements = s[1:-1].split(',')
    tmplist = []           #assemble temp list
    for elem in elements:
        if elem.startswith('"'):
            tmplist.append(elem[1:-1])
        else:
            tmplist.append(int(elem))

    return tmplist

它只处理字符串和整数,但足以满足我现在的需要。

7 个答案:

答案 0 :(得分:2)

您需要将return语句更改为。

return [int(elem) for elem in s[1:-1].split(',')] # Or map(int, s[1:-1].split(',')) 

答案 1 :(得分:2)

也许尝试ast.literal_eval

这是一个例子:

import ast

str1 = '[1,2,3,4,5]'
ast.literal_eval(str1)

输出将是这样的列表:

[1,2,3,4,5]

它不会在列表中包含逗号

答案 2 :(得分:1)

你也可以考虑使用ConfigParser(下面的Python 3示例,Python 2导入ConfigParser.ConfigParser,我相信):

from configparser import ConfigParser

parser = ConfigParser()
conf_file = os.path.join(dir_it's_located_in, 'config.txt')
parser.read(conf_file)

之后,它非常基本:您的整个配置文件被视为字典对象,所有配置行都是字典中的键:

firstname = parser['firstname']
lastname = parser['lastname']

您还可以在配置中设置部分,如下所示:

[employee info]
email = "something@something.com"
birthday = 10/12/98

您可以通过以下方式引用这些内容:

birthday = parser["employee info"]["birthday"]

而且,与往常一样,文档中有一些很好的例子:http://docs.python.org/3.2/library/configparser.html

答案 3 :(得分:0)

您可以使用split()

elif s.startswith('['):
    return [int(x) for x in s[1:-1].split(',')]

这将为您提供没有逗号的列表。

答案 4 :(得分:0)

elif s.startswith('['):
        return map(int,s[1:-1].split(","))

答案 5 :(得分:0)

目前,您正在将字符串转换为字符列表。你想这样做:

map(int, str[1:-1].split(','))

这将为您提供您所追求的整体列表。

答案 6 :(得分:0)

我喜欢使用ConfigParser作为@erewok提到的想法,这里是整个“解析器”

def parse(content):

    def parseList(content):
        # Recursive strategy
        listed = content.strip("[]").split(",")
        return map(parse, listed)

    def parseString(content):
        return content.strip("\"")

    def parseNumber(content):
        return int(content)

    def parse(content):
        if (content.startswith("\"")):
            return parseString(content)
        elif (content.startswith("[")):
            return parseList(content)
        elif (content.isdigit()):
            return parseNumber(content)

    # Create dictionary with values
    result = {}

    for line in content.splitlines():
        key, value = line.split("=",1)
        result[key] = parse(value)

    return result

我正在使用递归策略对列表中的元素进行子解析,以防列表中包含数字和字符串混合