基于分隔符的文件读取和词典创建

2024-05-21 09:05:09 发布

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

我有一个文件,有几行组成的项目。结构是一个类,后跟一个类别,后跟类中的先决条件。你知道吗

#Class, Category, Pre-requisites(amount of them can change)

MATH 2430, preprofessional, Math 2429|Math 2428,
Math 2431, professional, Math 2430|Math 2429|Math 2428,

我想要的是一个字典,其中类作为键,类别和先决条件作为列表中的值。像这样的

{'MATH 2430' : ['preprofessional', 'Math 2429','Math 2428']...... }

竖条是迎面而来的标志班级。学生我遇到的问题是,数字或垂直条分隔符可能会有所不同,因此前置类可能会因行而异。所以我不知道如何分割的基础上有多少垂直条

i wrote 
zdic = {}
pre_req = file.count("|") # to count how many vertical bars appear
if "|" in file :
prereq = pre_req
for line in file :
    course, category, prereq1(depending on bars...) = split("\W+",file)

先修课程的数目可能会有所不同,我该如何处理这个事实?根据有多少人,相应地分开来操纵和进入一个字典?你知道吗


Tags: 文件项目in字典先决条件countmath类别
2条回答

像这样:

txt='''\
MATH 2430, preprofessional, Math 2429|Math 2428,
Math 2431, professional, Math 2430|Math 2429|Math 2428,'''

d={}
for line in txt.splitlines():
    line=line.rstrip(',')
    li=[e.strip() for e in line.split(',')]
    d[li[0]]=[li[1]]+li[2].split('|')

print d 
# {'MATH 2430': ['preprofessional', 'Math 2429', 'Math 2428'], 'Math 2431': ['professional', 'Math 2430', 'Math 2429', 'Math 2428']}

或者,最好使用csv

import csv

d={}
with open('/tmp/test.csv') as f:
    for line in csv.reader(f, skipinitialspace=True):
        d[line[0]]=[line[1]]+line[2].split('|')
print d
# {'MATH 2430': ['preprofessional', 'Math 2429', 'Math 2428'], 'Math 2431': ['professional', 'Math 2430', 'Math 2429', 'Math 2428']}

只需使用split方法。假设您有正在解析的行的最后一部分(包含先决条件),那么如果使用带有适当分隔符的split方法(在本例中是|),就不需要计算任何内容。例如

案例1:

>>> pre_req = "Math 2430|Math 2429|Math 2428"
>>> pre_req.split("|")
['Math 2430', 'Math 2429', 'Math 2428']

案例2:

>>> pre_req = "Math 2429|Math 2428"
>>> pre_req.split("|")
['Math 2429', 'Math 2428']

split将拆分字符串,并将所有先决条件作为字符串列表提供给您,无论有多少个字符串。你知道吗

这里是你可以用来解析任何一行代码的一个简单例子。我使用了stripsplit方法。你知道吗

>>> line = "MATH 2430, preprofessional, Math 2429|Math 2428,"
>>> line = line.strip().split(",") # This gives you a list of strings
>>> d = {}
>>> d[line[0]] = [line[1]] + line[2].strip().split("|")
>>> d
{'MATH 2430': [' preprofessional', 'Math 2429', 'Math 2428']}

相关问题 更多 >