在python中从文件创建dicts

时间:2016-08-22 08:14:01

标签: python python-2.7 file input

例如,我的文件有多行,如

<<something>>   1, 5, 8
<<somethingelse>> hello
<<somethingelseelse>> 1,5,6

我需要用键创建dict

dict = { "something":[1,5,8], "somethingelse": "hello" ...}

我需要以某种方式阅读里面的内容&lt;&lt; &GT;&GT;并把它作为一个键,我还需要检查是否有很多元素或只有1.如果只有一个,那么我把它作为字符串。如果超过一个,那么我需要把它作为元素列表。 任何想法如何帮助我? 也许是regEx,但我对他们并不好。

我很容易创建def,它正在读取文件行,但不知道如何分隔这些值:

f = open('something.txt', 'r')
lines = f.readlines()
f.close()

def finding_path():
    for line in lines:
        print line

finding_path()
f.close()

有什么想法吗?谢谢:))

2 个答案:

答案 0 :(得分:1)

假设您的密钥始终是单个字,您可以使用split(char, maxSplits)。像下面的东西

import sys

def finding_path(file_name):
    f = open(file_name, 'r')
    my_dict = {}
    for line in f:
        # split on first occurance of space
        key_val_pair = line.split(' ', 1)
        # if we do have a key seprated by a space
        if len(key_val_pair) > 1:
            key = key_val_pair[0]
            # proceed only if the key is enclosed within '<<' and '>>'
            if key.startswith('<<') and key.endswith('>>'):
                key = key[2:-2]
                # put more than one value in list, otherwise directly a string literal
                val = key_val_pair[1].split(',') if ',' in key_val_pair[1] else key_val_pair[1]

                my_dict[key] = val
    print my_dict
    f.close()

if __name__ == '__main__':
    finding_path(sys.argv[1])

使用如下文件

<<one>> 1, 5, 8
<<two>> hello
// this is a comment, it will be skipped
<<three>> 1,5,6

我得到了输出

{'three': ['1', '5', '6\n'], 'two': 'hello\n', 'one': ['1', ' 5', ' 8\n']}

答案 1 :(得分:1)

请检查以下代码:

  • 使用正则表达式获取键和值

  • 如果值列表的长度为1,则将其转换为字符串。

override func layoutSubviews() {
    super.layoutSubviews()

    var frame = self.bounds
    frame.size.height = 45
    self.frame = frame
}

override func sizeThatFits(size: CGSize) -> CGSize {
    var size = super.sizeThatFits(size)
    size.height = 45
    return size
}

输出:

let navigationController = UINavigationController(navigationBarClass: nil, toolbarClass: Toolbar.self)