使用 Python 从 .txt 文件创建字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17714571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:59:29  来源:igfitidea点击:

Creating a dictionary from a .txt file using Python

pythondictionary

提问by miloJ

If you are given a .txt filewhich contains these contents:

如果你得到一个.txt file包含这些内容的:

James Doe 2/16/96 IT210 A BUS222 B PHY100 C
John Gates 4/17/95 IT101 C MATH112 B CHEM123 A
Butch Thomas 1/28/95 CS100 C MATH115 C CHEM123 B

How can you get it so it takes the class names and grades and puts them into an empty dictionary while ignoring the rest? I have code set up to read the .txt filebut got stuck. Any suggestions?

你怎么能得到它,所以它需要班级名称和成绩并将它们放入一个空字典而忽略其余部分?我已经设置了代码来读取.txt file但卡住了。有什么建议?

This is my code for opening the file:

这是我打开文件的代码:

def readFile():
    new_dict = {}
    myFile = open('Students.txt', 'r')
    for line in myFile:

回答by Ankur Ankan

li = []
with open("file.txt", 'r') as f:
    line = f.readline().split()
    while line:
        dict = {}
        dict[line[-6]] = line[-5]
        dict[line[-4]] = line[-3]
        dict[line[-2]] = line[-1]
        li.append(dict)
        line = f.readline().split()

li = [{'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}, {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}]

回答by Sukrit Kalra

Instead of making different variables for each student, why not use a list of dictionaries?

与其为每个学生制作不同的变量,为什么不使用字典列表呢?

See the code below :

请参阅下面的代码:

>>> dictList = []
>>> with open('Students.txt', 'r') as f:
        for line in f:
            elements = line.rstrip().split(" ")[3:]
            dictList.append(dict(zip(elements[::2], elements[1::2])))       
>>> dictList
[{'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}, {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}]

If you're looking to maintain the order as given in the txt file in the dictionary, then look into an OrderedDict.

如果您希望保持字典中 txt 文件中给出的顺序,请查看OrderedDict.

回答by Xirama

The below code does what you want.

下面的代码做你想要的。

import re

student = 'James Doe 2/16/96  IT210 A BUS222 B PHY100 C'
pattern = '([0-9]{1,2}/[0-9]{1,2}/[0-9]{1,2})'
end = re.search(pattern, student).end()
found = student[end+2:]
x = found.split(' ')
numberOfEntries = len(x) / 2
i = 0
Dict = {}

while i < numberOfEntries:
    Dict[x[i]] = x[i+1]
    i = i + 1

print Dict

回答by Hymanstine

dic={}
for line in myFile:
   info=line.split(' ')
   firstname=info[0]
   lastname=info[1]
   firstClass=info[3]
   firstgrade=info[4]
   secondClass=info[5]
   secondgrade=info[6]
   thirdClass=info[7]
   thirdGrade=info[8]
   gradeInfo={firstClass:firstgrade,secondClass:secondgrade,thirdClass:thirdgrade}
   name='%s %s' %(firstname,lastname)
   dic+={name,gradeInfo}

回答by seth

student_dict = {}
for line in open('input','r'):
    line2=line.split()
    name = ' '.join(line2[0:2])
    grades = line2[3:]
    grades_dict = {grades[i]:grades[i+1] for i in xrange(0,len(grades),2)}
    student_dict[name]=grades_dict

gives:

给出:

>>> student_dict
{'James Doe': {'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, 'Butch Thomas': {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}, 'John Gates': {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}}

回答by Tan Do

Anser:

解析器:

def readFile():
    new_dict = {}
    myFile = open('Students.txt', 'r')
    for line in myFile:
        line2=line.split()
        class1=line2[3]
        gra=line2[4]
        new_dict[class1]=gra