[英]extracting information from a text file and convert it into a dictionary
Python 的新手,對不起,如果這太簡單了,我通常使用 R 但想試試這個。 我正在嘗試將帶有學生編號、課程 ID(總共 7 門課程)和評分的 csv 文件轉換為字典。 它與其他問題不同,因為 csv 文件中的密鑰不是唯一值,它是根據學生評估的課程數量隨機復制的。 示例數據如下所示:
participant_id;course_id;rating
103;4;2
104;5;3.5
104;7;2.5
108;3;3.5
108;5;2
114;2;4.5
114;5;3.5
114;7;4.5
116;1;2
116;2;3
116;3;3
116;4;4
126;5;3
129;1;4
129;5;3.5
135;1;4.5
所以最佳結果應該是這樣的,學生人數將是鍵,值將是一個列表,其中 course_id 作為列表的索引,而 rating 作為值。 rest 只是不適用。
{'103': ['NA', 'NA', 'NA', 2.0, 'NA', 'NA', 'NA'],
'104': ['NA', 'NA', 'NA', 'NA', 3.5, 'NA', 2.5],
'108': ['NA', 'NA', '3.5, 'NA',2.0', 'NA', 'NA'],
'114': ['NA', 4.5, 'NA', 'NA', 3.5, 'NA', '4.5],
'116': [2.0, 3.0, 3.0, 4.0, 'NA', 'NA', 'NA'],
'126': ['NA', 'NA', 'NA', 'NA', 3.0, 'NA', 'NA'],
'129': [4.0, 'NA', 'NA', 'NA', '3.5, 'NA', 'NA'],
'135': [4.5, 'NA', 'NA', 'NA', 'NA', 'NA', 'NA']}
我嘗試使用 set() 提取學生編號,現在我擁有每個學生編號的唯一值,我所能做的就是用正確的鍵制作一個列表,但所有課程評分都是 NA,因為我不知道如何以分組提取 course_id 和 rating 並將它們放入列表中。 到目前為止,這是我的代碼:
def ratings(filename):
with open(filename) as fp:
buffer = fp.readlines()
stu_id = []
dic = {}
for i in (buffer):
stu_id.append(i.split(';')[0])
stu_id_set = list(set(stu_id))
for j in stu_id_set:
dic[j] = ['NA','NA','NA','NA','NA','NA','NA']
return dic
我們可以這樣做:
def ratings(filename):
d = {}
max_col = 0 # Number of columns needed. Maximum course_id.
idx_col_val_list = []
with open(filename) as fp:
fp.readline() # Ignore "participant_id;course_id;rating"
for line in fp.readlines():
line = line.strip()
idx, col, val = line.split(';')
col = int(col)
val = float(val)
max_col = max(max_col, col)
idx_col_val_list.append((idx, col, val))
for idx, col, val in idx_col_val_list:
if idx not in d:
d[idx] = ['NA'] * max_col
d[idx][col - 1] = val
return d
ans = ratings('input.txt')
assert ans == {
'103': ['NA', 'NA', 'NA', 2.0, 'NA', 'NA', 'NA'],
'104': ['NA', 'NA', 'NA', 'NA', 3.5, 'NA', 2.5],
'108': ['NA', 'NA', 3.5, 'NA',2.0, 'NA', 'NA'],
'114': ['NA', 4.5, 'NA', 'NA', 3.5, 'NA', 4.5],
'116': [2.0, 3.0, 3.0, 4.0, 'NA', 'NA', 'NA'],
'126': ['NA', 'NA', 'NA', 'NA', 3.0, 'NA', 'NA'],
'129': [4.0, 'NA', 'NA', 'NA', 3.5, 'NA', 'NA'],
'135': [4.5, 'NA', 'NA', 'NA', 'NA', 'NA', 'NA'],
}
這是使用pandas
和字典的緊湊方法:
import pandas as pd
df = pd.read_csv('your_csv_file.csv')
# build a list of dictionaries
# each element will lool like {'participant_id':104, 'course_id':4, 'rating':2}
records = df.to_dict(orient='records')
# initialize the final dictionary
# assign a 7-element list to each participant, filled with zeros
performance = {i['participant_id']:7*[0] for i in records}
# populate the final dictionary
for r in records:
performance[r['participant_id']][r['course_id']] = r['rating']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.