Python读取文本文件为字典,字符串列表

2024-06-25 05:57:22 发布

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

我正在试着把一个文本文件读入词典。 文本文件包含人名、网络和朋友的姓名。 字典的关键是人的名字,而值是这个人的网络 以下是文本文件:

Pritchett, Mitchell\n
Law Association\n
Dunphy, Claire\n
Tucker, Cameron\n
Dunphy, Luke\n
\n\n
Tucker, Cameron\n
Clown School\n
Wizard of Oz Fan Club\n
Pritchett, Mitchell\n
Pritchett, Gloria\n
\n\n
Dunphy, Alex\n
Orchestra\n
Chess Club\n
Dunphy, Luke\n

这是我所做的

^{pr2}$

在lst[0]中,'if“\n”和“,”行有一个错误。它说列表索引超出范围。 请帮帮我。我搞不清这个代码有什么问题。在


Tags: 网络字典朋友名字关键词典姓名文本文件
3条回答

出现这个错误是因为您将lst初始化为空[],然后检查第一个不存在的元素。在

你说你想把你的文件变成字典,我建议你用这个更简单的代码:

import re  # import regex library
# open the file and import your data
f = open('data', 'r')
data = f.read()
f.close()
# initialize your data to be processed
dict = {}
data = data.replace('\\n', '') # remove \n characters
data = data.split('\n\n')      # split it into blocks
for block in data:
    block = block.split('\n')  # split each bock into lines
    nets = []
    for line in block:
        if ',' not in line and line != '': # find networks
            nets.append(line)
    block[0] = re.sub(r'(\w+),\s(\w+)', r'\2, \1', block[0])  # ADDED to switch first name and last name
    dict.update({block[0]: nets})   # update the result dictionary
print dict

这将为您的建议文件示例提供以下结果:

^{pr2}$

如果这不是你想要的,请详细描述它是什么。在

编辑:为了切换first name和{},您可以在更新字典之前添加这一行来进行切换。我在上面的代码中添加了这一行,它使用了一个regex(别忘了添加“import re”,就像在我代码的开头):

'(\w+),\s(\w+)' # used to find the first name and last name and store them in \1 and \2 match groups.
'\2, \1'        # to replace the place of the match groups as required.
 OR '\2 \1'     # if you don't want the comma 

你可以随意操作它,例如:你可以移除,之类的东西。在

切换后,输出将变成:

{'Alex, Dunphy': ['Orchestra', 'Chess Club'], 'Cameron, Tucker': ['Clown School', 'Wizard of Oz Fan Club'], 'Mitchell, Pritchett': ['Law Association']}

编辑:firstlast名称之间切换的另一种方法(删除“import re”和先前添加的行,并将其替换为具有相同缩进的这三行):

s = block[0].split(', ')
s.reverse()
block[0] = ', '.join(s)  # or use ' '.join(s) if you don't want the comma

希望这有帮助。在

因为第一次通过循环时,您试图访问lst[0],而lst仍然是[]。在

至少第一行,lst是空列表([])。 您应该首先向lst追加一些值。在


也许,你想做以下事情:

if "\n" and "," in lst[0]:if "\n" and "," in line[0]: 你说

elif "," not in lst[1:]:elif "," not in line[1:]:

最后一行中的new_person_friends未定义。你需要把它修好。在


当行为“\n”时,lst将在networks更新后清除。
您的数据有“\n\n”。这意味着两个连续的空行。 因为“\n”第一个“\n”列表中的第一个“\n”为空 您需要修复代码以避免出现这样的问题:if line == '\n' and lst != []:

相关问题 更多 >