坚持尝试获取行文件的特定部分并将其存储在字典中—python
我是python(以及本网站)的初学者&在过去的几个小时里,我一直在尝试获取文件的特定方面,将文件的两个方面组合成字典格式。(ex)123456:无名氏 这就是我的意思,如果这是示例文件:坚持尝试获取行文件的特定部分并将其存储在字典中—python,python,file,loops,dictionary,Python,File,Loops,Dictionary,我是python(以及本网站)的初学者&在过去的几个小时里,我一直在尝试获取文件的特定方面,将文件的两个方面组合成字典格式。(ex)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,4
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个类别,第一行告诉你这些类别的顺序,然后后面的所有行都是每个学生信息的巨大文件。这仅仅是两行两个学生,但是文件中有很多学生。我想做的是把学生id和学生姓名以-student id:student name的格式放入字典中。还有\n个字符&我也需要去掉它们 这就是我到目前为止所做的:
def student_id(filename):
dictionary={}
file=open(filename,"r")
content=filename.readlines()
for line in content:
我假设我必须使用for循环,但我无法想象如何,我真的会因为沮丧而哭泣。非常感谢您的帮助&因为我是一名初学者,所以我想要非常简单的代码,以尽可能少的Python方式,非常感谢您 类似于:
with open("student.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
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}
这将读取文件的每一行,并将其存储在列表content
中。
EDIT:如果您只是将
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
由于您使用的是
csv
数据,因此可以使用它简化文件的解析:
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"]
Python是用来处理包含逗号分隔值的文件的,它取代了pprint
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}
或者(可能是你要求的方式):
这不是一个真正的蟒蛇式的方法。一旦你了解了这一点,你会做如下事情:
with open("student.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
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:]]}
该文件看起来像csv格式,您可以使用它的.txt文件format@Jasper文件扩展名
.csv
字面上代表“逗号分隔值”。Python的csv
模块设计用于处理这种格式的文件。非常感谢,但是有没有办法不使用“with”&最后一行更简单,因为我们没有使用“[x.strip()for x in content]”@Jasper it,不是很高级,只是对列表中的所有元素应用一些逻辑的一种简洁方式。@exo 1:我不认为这回答了最初提出的问题和2。只需对f中的行执行,而不执行readlines()
将提高内存效率,减少代码中的噪音。“学生id&学生姓名,并将其以学生id:student name
的格式放入字典”-我想您可能误解了OP的目的,我想他们希望结果是一本字典,其中键是学生ID,值是名字。@Tadhgmandald Jensen啊,我明白了。更新了。谢谢,我一直在寻找的是“非蟒蛇”方式:)