【问题标题】:Stuck with trying to take specific parts of a file of lines and storing them in a dictionary - python坚持尝试获取行文件的特定部分并将它们存储在字典中 - python
【发布时间】:2017-02-13 03:45:35
【问题描述】:

我是 python(和这个网站)的初学者,在过去的几个小时里,我一直在尝试获取文件的特定方面,将文件的两个方面组合成字典格式。例如)123456:约翰·多伊

这就是我的意思,如果这是示例文件:

student_id,student_birthdate,student_address,student_contact,student_name

123456,06-10-1994,123 BirdWay Drive, (123)123-4567,John Doe

789123,03-02-1995,465 Creek Way,(000)456-7890,Jane Doe

附:上面的行中不应该有空格^^我只把它们放在那里,这样你就可以看到每一行是如何分类的。 所以你可以看到有 5 个类别,第一行告诉你这些类别的顺序,然后后面的所有行只是每个学生信息的巨大文件。这些只是 2 行 2 名学生,但文件很大,里面塞满了很多学生。我正在尝试做的是获取 student_id 和学生姓名,并将它们以格式 - 学生 ID:学生姓名放入字典中。还有 \n 个字符,我也需要删除它们。

这是我目前所拥有的:

def student_id(filename):
    dictionary={}
    file=open(filename,"r")
    content=filename.readlines()
    for line in content:

我假设我必须使用 for 循环,但我不知道怎么做,我真的要因沮丧而哭泣。非常感谢任何帮助,因为我是初学者,所以我想要非常简单的代码,所以尽可能以最少的 Python 方式,非常感谢!

【问题讨论】:

  • 那个文件看起来像 csv 格式,也许你可以使用csv module
  • 它是一个 .txt 文件格式
  • @Jasper 文件扩展名.csv 字面意思是“逗号分隔值”。 Python 的csv 模块旨在处理该格式的文件。

标签: python file loops dictionary


【解决方案1】:

Python 的csv module 旨在处理包含逗号分隔值的文件。

import csv

def student_id(filename):
    with open(filename, mode='r', encoding='utf-8') as f:
        reader = csv.DictReader(f, delimiter=',')
        data = list(reader)
    data = {item["student_id"]:item["student_name"] for item in data}

或者(可能是您要求的方式):

def student_id(filename):
    results = {}
    f = open(filename, 'r')
    f.readline() # skip the header
    lines = f.readlines()
    f.close()
    for line in lines:
        item = line.strip().split(",")
        results[item[0]] = item[4]
    return results

这并不是真正的 Pythonic 方式。一旦你了解它,你会做这样的事情:

def student_id(filename):
    with open(filename, 'r') as f:
        items = [item.strip().split(",") for item in f.readlines()[1:]]
        return {item[0]:item[4] for item in items}

或者,如果你感觉特别邪恶:

def student_id(filename):
    with open(filename, 'r') as f:
        return {item[0]:item[4] for item in [item.strip().split(",") for item in f.readlines()[1:]]}

【讨论】:

  • "student_id & the student name 并以格式 - student id : student name" 将它们放入字典中 - 我想你可能误解了 OP 的目的,我认为他们希望结果是一个字典,其中键是学生 ID,值是名称。
  • @TadhgMcDonald-Jensen 啊,我明白了。已更新。
  • 感谢“非pythonic”方式是我正在寻找的:)
【解决方案2】:

由于您使用的是csv 数据,您可以使用csv.DictReader 来简化文件的解析:

import pprint #for the sake of this demo

import csv
filename = "test.txt" #for the sake of this demo

with open(filename, "r") as f:
    #it will automatically detect the first line as the field names
    for details in csv.DictReader(f):
        pprint.pprint(dict(details)) #for this demo

使用您提供的示例文本,输出如下:

{'student_address': '123 BirdWay Drive',
 'student_birthdate': '06-10-1994',
 'student_contact': ' (123)123-4567',
 'student_id': '123456',
 'student_name': 'John Doe'}
{'student_address': '465 Creek Way',
 'student_birthdate': '03-02-1995',
 'student_contact': '(000)456-7890',
 'student_id': '789123',
 'student_name': 'Jane Doe'}

所以要映射id:name,您只需要这样做:

 id = details["student_id"]
 dictionary[id] = details["student_name"]

代替pprint

【讨论】:

    【解决方案3】:

    类似:

    with open("student.txt") as f:
        content = f.readlines()
    content = [x.strip() for x in content]
    

    这将读取文件的每一行,并将其存储在列表content 中。

    编辑:如果您只是将 f.readlines() 的每个元素附加到列表中,您将在列表中每个元素的末尾获得换行符 \n。这就是为什么上面的代码是一个很好的方法;您不必担心删除\n。如果您想要没有 with 声明的东西,您可以尝试:

    f = open("student.txt") # Open the file
    List = [] # List to store lines in
    
    for row in f: # Go through each line in the file
        row = row.translate(None, '\n') # Remove \n from the line
        List.append(row) # Add the line to the list
    

    【讨论】:

    • 非常感谢,但是有没有办法没有“with”和最后一行更简单,因为我们没有使用“[x.strip() for x in content]”
    • @Jasper 它被称为list comprehension,不是很高级,只是将一些逻辑应用于列表的所有元素的一种紧凑方式。
    • @exo 1:我认为这不能回答最初提出的问题,并且 2. 只执行 for row in f 而不执行 readlines() 会提高内存效率并减少代码中的噪音。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多