【问题标题】:How to make a dictionary entry from each line in a text file?如何从文本文件中的每一行创建一个字典条目?
【发布时间】:2019-10-02 10:58:30
【问题描述】:

所以,我有一个包含以下信息的文本文件:

student_num1 student_name1 student_grade1
student_num2 student_name2 student_grade2
student_num3 student_name3 student_grade3

我想要做的是我想将此文本文件的每一行作为具有这种格式的字典条目:

students = { student_num1: [student_name1, student_grade1], student_num2: [student_name2, student_grade2], student_num3: [student_name3, student_grade3] }

基本上,该行的第一个字符串应该是键,它旁边的 2 个字符串是值。但我不知道如何让 python 分隔每一行中的字符串并将它们分配为字典的键和值。

编辑: 所以,我尝试了一些代码:(我看到了你所有的解决方案,我认为它们肯定会起作用,但我也想学习创建我的解决方案,所以如果你能检查我的,我将非常感激!)

for line in fh:
    line = line.split(";")
    student_num = line[0]
    student_name = line[1]
    student_grade = line[2]

    count =+ 1
    direc[student_num] = [student_name,student_grade]
    student_num = "student_num" + str(count)
    student_grade = "student_grade" + str(count)
    student_name = "student_name" + str(count)

print(direc)

问题是我在第 10 行或这部分“student_name = line[1]”上收到列表索引超出范围的错误

编辑:谢谢大家!您建议的每一个解决方案都有效!我也修复了我自己的解决方案。这是固定的(正如@norok2 所建议的那样):

for line in fh:
    line = line.split(" ")
    student_num = line[0]
    student_name = line[1]
    student_grade = line[2]

    count =+ 1
    direc[student_num] = [student_name,student_grade]
    student_num = "student_num" + str(count)
    student_grade = "student_grade" + str(count)
    student_name = "student_name" + str(count)

【问题讨论】:

  • 您搜索了什么,找到了什么?基于此,您尝试了什么,又是如何失败的?
  • @tripleee 我已经搜索了一段时间,但似乎找不到解决方案。我的想法是我想尝试将每一行作为一个列表,然后将该列表用作我的字典的条目,但问题是 1:我不知道分隔每一行并使每一行成为列表的正确语法和 2:我也不知道如何让 python 将列表中的每个元素识别为键和值
  • 所以你可以edit这个问题来展示你如何open文件并遍历这些行,并标记你被卡住的地方。提示:split()

标签: python python-3.x string dictionary


【解决方案1】:

作为字典理解:

with open("data.txt", "r") as f:
    students = {k:v for k, *v in map(str.split, f)}

解释:

文件对象f 已经是一个迭代器(产生每一行),我们想要拆分行,所以我们可以使用map(str.split, f)(line.split() for line in f)。 之后我们知道,第一项是字典的键,其余项是值。我们可以为此使用拆包。拆包示例:

>>> a, *b = [1,2,3]
>>> a
1
>>> b
[2, 3]

然后我们使用推导式来构建带有我们在解包中捕获的值的字典。 dict comprehension 是建立字典的表达式,例如:

>>> {x:x+1 for x in range(5)}
{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}

例子,

文件data.txt:

student_num1 student_name1 student_grade1 
student_num2  student_name2 student_grade2 
student_num3 student_name3 student_grade3

读完

>>> with open("data.txt", "r") as f:
...     students = {k:v for k, *v in map(str.split, f)}
... 
>>> students
{'student_num1': ['student_name1', 'student_grade1'], 'student_num2': ['student_name2', 'student_grade2'], 'student_num3': ['student_name3', 'student_grade3']}

【讨论】:

  • 它有效,谢谢!但是你能解释一下代码在 with open... 部分之后的作用吗?
  • @Gatts,当然,查看解释并随时提问!
  • 我现在明白了!非常感谢您的帮助:))
【解决方案2】:

我当前的方法使用文件处理以读取模式打开文件,然后读取文件中存在的行。然后对于每一行,删除额外的新行和空格并将其拆分为空格,以创建一个列表。然后使用解包将单个值存储为key,并将2个值的列表存储为value。为字典添加了值。

temp.txt

student_num1 student_name1 student_grade1
student_num2 student_name2 student_grade2
student_num3 student_name3 student_grade3

ma​​in.py

d = dict()
with open("temp.txt", "r") as f:
  for line in f.readlines():
    key, *values = line.strip().split(" ")
    d[key] = values
  print(d)

输出

{'student_num1': ['student_name1', 'student_grade1'], 'student_num2': ['student_name2', 'student_grade2'], 'student_num3': ['student_name3', 'student_grade3']}

【讨论】:

    【解决方案3】:
    with open('data.txt') as f:
      lines = f.readlines()
    d = {}
    for line in lines:
      tokens = line.split()
      d[tokens[0]] = tokens[1:]
    print(d)
    

    我希望这是可以理解的。要将行拆分为不同的标记,我们使用 split1 函数。

    【讨论】:

    • 您好!你能检查我自己的解决方案吗?我已经编辑了我的帖子。编辑:我也试过你的代码,它有效!谢谢!
    • @Gatts 我看到您正在使用 line.split(";")。这将根据字符';'拆分字符串。但是,我看到您正在使用学生编号、年级和编号之间的空格,因此您应该调用不带参数的 split 或使用空格 (' ') 作为参数。
    【解决方案4】:

    您的解决方案出现该错误的原因是您的行似乎不包含字符 ;,但您尝试使用 line = line.split(";") 按该字符进行拆分。

    您应该将其替换为:

    • line = line.split(" ") 用空格符分割

    • line = line.split(";") 被任何空白字符分割

    不过,如需更优雅的解决方案,请参阅 here

    【讨论】:

      【解决方案5】:

      你有没有尝试过像这样简单的事情:

      d = {}
      with open('students.txt') as f:
          for line in f:
              key, *rest = line.split()
              d[key] = rest
      
      print(d)
      # {'student_num1': ['student_name1', 'student_grade1'], 'student_num2': ['student_name2', 'student_grade2'], 'student_num3': ['student_name3', 'student_grade3']}
      

      【讨论】:

        【解决方案6】:

        file.txt:

        student_num1 student_name1 student_grade1
        student_num2 student_name2 student_grade2
        student_num3 student_name3 student_grade3
        

        Main.py:

        def main():
            file = open('file.txt', 'r')
            students = {}
            for line in file:
                fields = line.split(" ")
                fields[2] = fields[2].replace("\n", "")
                students[fields[1]] = [fields[0], fields[2]]
        
            print(students)
        main()
        

        输出:

        {'student_name1': ['student_num1', 'student_grade1'], 'student_name2': ['student_num2', 'student_grade2'], 'student_name3': ['student_num3', 'student_grade3']}
        

        【讨论】:

          猜你喜欢
          • 2016-03-09
          • 2011-05-20
          • 2020-05-11
          • 1970-01-01
          • 2021-11-01
          • 1970-01-01
          • 2013-01-05
          • 2021-12-14
          • 1970-01-01
          相关资源
          最近更新 更多