![](/img/trans.png)
[英]create a nested dictionary from the input given in a text file in python
[英]Create a dictionary from a given string in a text file
我有一个带有以下格式的字符串的文件:.B:13&A:4&I:1&I:!&H:|-|&H:} {&B:!3&H:[-] &&
它以“。”开头。 以“&”结尾,以“&”分隔每个条目键值对,最后以“:”分隔每个键与其对应的值
这是我到目前为止的内容:
//读取数据
filehndl = open("text.dat") filedata = filehndl.read() filehndl.close()
但我不确定如何剥离和拆分数据以创建字典。 任何帮助,将不胜感激!
您可以使用以下命令删除第一个和最后一个字符:
filedata = filedata[1:-1]
然后拆分为:
entries = filedata.split('&')
然后拆分条目并将其放入字典中:
out_dict = {}
for entry in entries:
entry_array = entry.split(':')
out_dict[entry_array[0]] = entry_array[1]
所以总共
filehndl = open("text.dat")
filedata = filehndl.read()
filedata = filedata[1:-1]
entries = filedata.split('&')
out_dict = {}
for entry in entries:
entry_array = entry.split(':')
out_dict[entry_array[0]] = entry_array[1]
# out_dict is what you now want to work with
filehndl.close()
1个线性版本假定您的文件数据也将是1个线性
1st用&
分割dict项,然后剥离.
和&
,然后构建dict,将键值对分割为:
filedata = r'.B:13&A:4&I:1&I:!&H:|-|&H:}{&B:!3&H:[-]&&'
d = dict( i.split(':') for i in filedata.strip('.&\r\n').split('&') )
# {'A': '4', 'I': '!', 'B': '!3', 'H': '[-]'}
但这并不会影响具有相同键的重复项,例如,您重复了键B
,后面的B:!3
将覆盖之前的B:13
我将假设您的文件只有一行,并且您不处理引号,因此您可以使用生成器理解来做到这一点:
with open("yourfile.txt") as file:
data = file.read().strip()
if data.startswith(".") and data.endswith("&"):
clean = data.lstrip(".").rstrip("&")
print dict(item.split(":") for item in clean.split("&"))
重要的一行是:
dict(item.split(":") for item in clean.split("&"))
这将用&
字符分割字符串,然后再次用:
字符分割,以最终“转换”字典中的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.