在python中从文件创建dict

2024-10-03 23:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个多行文件,比如

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

我需要用钥匙创建dict

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

我需要以某种方式读取里面的内容,并将其作为一个键,还需要检查元素是否很多或只有1个。如果只有一个,我就把它当作弦。如果超过一个,那么我需要把它作为一个元素列表。 有什么办法帮我吗? 也许是正则表达式,但我对它们不太好。你知道吗

我很容易地创建了def,它读取一个文件行,但不知道如何分离这些值:

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

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

finding_path()
f.close()

有什么想法吗?谢谢:)


Tags: 文件path元素helloclosedef方式line
3条回答

假设您的键总是单个单词,您可以使用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']}

我的答案与Dinesh的类似,我添加了一个函数,如果可能的话,可以将列表中的值转换为数字,并添加了一些错误处理,这样如果一行不匹配,就会给出有用的警告。你知道吗

import re
import warnings

regexp =re.compile(r'<<(\w+)>>\s+(.*)')

lines = ["<<something>>   1, 5, 8\n",
         "<<somethingelse>> hello\n",
         "<<somethingelseelse>> 1,5,6\n"]

#In real use use a file descriptor instead of the list
#lines = open('something.txt','r')

def get_value(obj):
    """Converts an object to a number if possible, 
    or a string if not possible"""
    try:
        return int(obj)
    except ValueError:
        pass
    try:
        return float(obj)
    except ValueError:
        return str(obj)

dictionary = {}

for line in lines:    
    line = line.strip()
    m = re.search(regexp, line)
    if m is None:
        warnings.warn("Match failed on \n   {}".format(line))
        continue
    key = m.group(1)
    value = [get_value(x) for x in m.group(2).split(',')]
    if len(value) == 1: 
        value = value[0]
    dictionary[key] = value

print(dictionary)

输出

{'something': [1, 5, 8], 'somethingelse': 'hello', 'somethingelseelse': [1, 5, 6]}

请检查以下代码:

  • 使用regex获取键和值

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

import re
demo_dict = {}

with open("val.txt",'r') as f:
    for line in f:
          m= re.search(r"<<(.*?)>>(.*)",line)
          if m is not None:
               k = m.group(1)
               v = m.group(2).strip().split(',')
               if len(v) == 1:
                    v = v[0]
               demo_dict[k]=v
print demo_dict

输出:

C:\Users\dinesh_pundkar\Desktop>python demo.Py
{'somethingelseelse': [' 1', '5', '6'], 'somethingelse': 'hello', 'something': [
'   1', ' 5', ' 8']}

相关问题 更多 >