简体   繁体   English

从.txt文件创建字典

[英]Creating a dictionary from a .txt file

I have a .txt file with list of users, it goes like this: 我有一个带有用户列表的.txt文件,它像这样:

ID - NAME(S) - LAST NAME(S) - LOGIN - PASSWORD

0001 - Juan Carlos - Botero Mora - jcboterom - snf23jn4

.

.

So, I need to create a dictionary like this: 因此,我需要创建一个像这样的字典:

{'0001': ['Juan Carlos', 'Botero Mora', 'jcboterom', 'snf23jn4']}

The code is 该代码是

def dict():
with open('admins.txt', 'r') as document:
    answer = {}
    for line in document:
        if line.strip():
            key, value = line.split(None, 1)
            answer[key] = value.split()
return answer

But this is what I get: 但这就是我得到的:

{'0001': ['-', 'Juan', 'Carlos', '-', 'Botero', 'Mora', '-', 'jcboterom', '-', 'snf23jn4']

What's wrong? 怎么了?

All you need is to split the value again with the delimiter - rather than space. 您所需要做的就是用定界符-而不是空格)再次分割value

>>> key, value = line.split('-', 1)
>>> answer[key] = value.split(' - ')
>>> answer
{'0001 ': [' Juan Carlos', 'Botero Mora', 'jcboterom', 'snf23jn4']}

From the python docs 来自python文档

str.split([sep[, maxsplit]]) Return a list of the words in the string, using sep as the delimiter string. str.split([sep[, maxsplit]])使用sep作为分隔符字符串,返回字符串中单词的列表。

The issue is that you are splitting your strings at all whiteplaces , which is what str.split() does. 问题是您要在所有str.split()拆分字符串,这就是str.split()作用。 Instead you should split them at '-' and then strip off the whitespace from the result. 相反,您应该在'-'处将它们分开,然后从结果中去除空格。

Code - 代码-

def dict():
    with open('admins.txt', 'r') as document:
        answer = {}
        for line in document:
            if line.strip():
                key, value = line.split('-', 1)
                answer[key.strip()] = [v.strip() for v in value.split('-')]
    return answer

Demo - 演示-

>>> s = '0001 - Juan Carlos - Botero Mora - jcboterom - snf23jn4'
>>> key,value = s.split('-',1)
>>> answer = {}
>>> answer[key.strip()] = [v.strip() for v in value.split('-')]
>>> answer
{'0001': ['Juan Carlos', 'Botero Mora', 'jcboterom', 'snf23jn4']}

split() can go with pattern. split()可以和pattern一起使用。 Here you can use ' - ' 在这里您可以使用' - '

>>> s = '0001 - Juan Carlos - Botero Mora - jcboterom - snf23jn4'
>>> s
'0001 - Juan Carlos - Botero Mora - jcboterom - snf23jn4'
>>> [key, value] = s.split(' - ', 1)
>>> key
'0001'
>>> value
'Juan Carlos - Botero Mora - jcboterom - snf23jn4'
>>> value = value.split(' - ')
>>> value
['Juan Carlos', 'Botero Mora', 'jcboterom', 'snf23jn4']

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

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