简体   繁体   English

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

[英]How to convert text format list into a python list

I am getting various data types from a config file and adding them to a dictionary. 我从配置文件中获取各种数据类型,并将它们添加到字典中。 but I am having a problem with lists. 但是我在列表上有问题。 I want to take a line with text: alist = [1,2,3,4,5,6,7] and convert into a list of integers. 我想用一行文本: alist = [1,2,3,4,5,6,7]并转换为整数列表。 But I am getting 但是我越来越

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

How can I fix this? 我怎样才能解决这个问题?

Here is config.txt: 这是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]

Here is my code to parse: 这是我要解析的代码:

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

Here is my printed output: 这是我的打印输出:

{'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'}

Update. 更新。

Thanks for the feedback. 感谢您的反馈。 I realised that I could also get heterogeneous list so changed list part to: 我意识到我也可以获得异构列表,因此将列表部分更改为:

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

It only handles strings and integers but is good enough for what I need right now. 它仅处理字符串和整数,但足以满足我现在的需求。

您需要将return语句更改为。

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

maybe try ast.literal_eval 也许尝试ast.literal_eval

here is an example: 这是一个例子:

import ast

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

output will be a list like this: 输出将是这样的列表:

[1,2,3,4,5]

it wont include the commas in the list 它不会在列表中包含逗号

You might also consider using ConfigParser (Python 3 example below, Python 2 imports ConfigParser.ConfigParser , I believe): 您可能还考虑使用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)

After that, it's really basic: your whole config file is treated like a dictionary object and all configuration lines are keys in the dictionary: 之后,这才是真正的基础:将整个配置文件视为字典对象,所有配置行都是字典中的键:

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

You can also set up sections in your configuration like so: 您还可以像这样在配置中设置部分:

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

And you can reference these in the following way: 您可以通过以下方式引用它们:

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

And, as always, there are some great examples in the docs: http://docs.python.org/3.2/library/configparser.html 而且,一如既往,文档中也有一些很棒的例子: http : //docs.python.org/3.2/library/configparser.html

You can use split() : 您可以使用split()

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

This will give you the list without the commas. 这将为您提供不带逗号的列表。

ummm

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

Currently you're converting a string to a list of characters. 当前,您正在将字符串转换为字符列表。 You want to be doing this: 您想这样做:

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

That will give you the list of ints you are after. 这将为您提供所需的整数列表。

I like the idea of using ConfigParser as @erewok mentioned, here's the whole "parser" 我喜欢使用@erewok提到的ConfigParser的想法,这里是整个“解析器”

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

I'm using a recursive strategy to sub-parse elements within the list you are getting, in case the list comes with numbers and strings mixed 我正在使用递归策略对要获取的列表中的元素进行子解析,以防列表中混有数字和字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM