我正在嘗試讀取格式如下的文本檔案:
student
first name: John
last name: Doe
grade: 9
gpa: 4.0
school
name: Richard High School
city: Kansas City
####
student
first name: Jane
last name: Doe
grade: 10
gpa: 3.0
school
name: Richard High School
city: Kansas City
到 Python 字典中。試圖讓最終結果看起來像:
{0:{'student':{'first name': 'John',
'last name': 'Doe',
'grade': '9',
'gpa': '4.0'},
"school": {'name': 'Richard High School',
'city': 'Kansas City'},
1:{'student':{'first name': 'Jane',
'last name': 'Doe',
'grade': '10',
'gpa': '3.0'},
'school': {'name': 'Richard High School',
'city': 'Kansas City'}
}
到目前為止,我知道如何處理內部鍵:
with open('<filename>') as f:
dict = {}
for line in f:
x, y = line.split(": ")
dict[x] = y
print(dict)
但除此之外,我被困住了。
uj5u.com熱心網友回復:
如果您的資料完全按照您撰寫的模式進行排列,并且您不介意使用扁平字典,則每個學生一本:
pattern = re.compile(r"""
student
first name: (?P<first_name>.*)
last name: (?P<last_name>.*)
grade: (?P<grade>\d*)
gpa: (?P<gpa>\d .?\d*)
school
name: (?P<school>.*)
city: (?P<city>.*)""".strip())
with open(<filename>, "r") as f:
data = f.read()
students = [match.groupdict() for match in pattern.finditer(data)]
輸出:
[{'first_name': 'John',
'last_name': 'Doe',
'grade': '9',
'gpa': '4.0',
'school': 'Richard High School',
'city': 'Kansas City'},
{'first_name': 'Jane',
'last_name': 'Doe',
'grade': '10',
'gpa': '3.0',
'school': 'Richard High School',
'city': 'Kansas City'}]
我沒有看到您想要的資料結構的好處,因此我建議一些更有利于表格資料分析的東西。
編輯:現在我們正在談論熊貓,
In [4]: df = pd.DataFrame(students)
In [5]: df
Out[5]:
first_name last_name grade gpa school city
0 John Doe 9 4.0 Richard High School Kansas City
1 Jane Doe 10 3.0 Richard High School Kansas City
獲取每個年級的學生人數:
In [6]: df.groupby("grade").size()
Out[6]:
grade
10 1
9 1
dtype: int64
您還可以按任意數量的列分組,例如按年級和學校:
In [7]: df.groupby(["grade", "school"]).size()
Out[7]:
grade school
10 Richard High School 1
9 Richard High School 1
dtype: int64
uj5u.com熱心網友回復:
這是一個可能的解決方案:
import re
file = open("a.txt")
dictionaryMain = {}
dictionaryElement = {}
dictionaryStudent = {}
dictionarySchool = {}
text = file.read()
elements = text.split("####")
i = 0
for element in elements:
firstName = re.search('first name: (. )', text).group(1)
lastName = re.search('last name: (. )', text).group(1)
grade = re.search('grade: (. )', text).group(1)
gpa = re.search('gpa: (. )', text).group(1)
name = re.search('name: (. )', text).group(1)
city = re.search('city: (. )', text).group(1)
dictionaryStudent['first name'] = firstName
dictionaryStudent['last name'] = lastName
dictionaryStudent['grade'] = grade
dictionaryStudent['gpa'] = gpa
dictionarySchool['name'] = name
dictionarySchool['city'] = city
dictionaryElement['student'] = dictionaryStudent
dictionaryElement['school'] = dictionarySchool
i = i 1
dictionaryMain[i] = dictionaryElement
print(dictionaryMain)
輸入檔案:
student
first name: John
last name: Doe
grade: 9
gpa: 4.0
school
name: Richard High School
city: Kansas City
####
student
first name: Jane
last name: Doe
grade: 10
gpa: 3.0
school
name: Richard High School
city: Kansas City
####
student
first name: Jane
last name: Doe
grade: 10
gpa: 3.0
school
name: Richard High School
city: Kansas City
輸出:
{
1: {
'student': {
'first name': 'John',
'last name': 'Doe',
'grade': '9',
'gpa': '4.0'
},
'school': {
'name': 'John',
'city': 'Kansas City'
}
},
2: {
'student': {
'first name': 'John',
'last name': 'Doe',
'grade': '9',
'gpa': '4.0'
},
'school': {
'name': 'John',
'city': 'Kansas City'
}
},
3: {
'student': {
'first name': 'John',
'last name': 'Doe',
'grade': '9',
'gpa': '4.0'
},
'school': {
'name': 'John',
'city': 'Kansas City'
}
}
}
我不完全知道您的用例是什么,但是如果您有如此嚴格的格式,您應該真正考慮使用資料類。
uj5u.com熱心網友回復:
import re
temp = 0
data = {temp:{}}
with open('txt.txt') as f:
for line in f:
if len(line.strip()) == 0:
continue
if re.match("^[^:]*:.*$", line):
key, value = line.split(':', 1)
data[temp][main_key][key.strip()] = value.strip()
elif re.match("^[^\#]*$", line):
main_key = line.strip()
if main_key in (data[temp].keys()):
temp = 1
data[temp] = {}
data[temp][main_key] = {}
如果我正確地實作了你的目標,這就是答案。但要小心,它是基于正則運算式的,您現在可以在 regex101.com 中了解更多資訊
首先,如果,我會跳過類似于“”并且充滿空的線條!(斷線)第二,我檢查行格式是否像“鍵:值”,如果不是,那么它是主鍵,我將它添加到主字典中,否則,我將它添加到主字典中的最后一個字典中
uj5u.com熱心網友回復:
您可以這樣做,但請記住,此方法非常特定于原始問題中定義的輸入和輸出:
d = dict()
k = 0
with open('foo.txt') as infile:
for line in map(str.strip, infile):
if len(line) > 0:
match line:
case 'student':
td = dict()
d[k] = {line: td}
k = 1
case 'school':
td[line] = dict()
td = td[line]
case _:
k_, *v = line.split(':')
if v:
td[k_] = v[0].strip()
print(d)
輸出:
{0: {'student': {'first name': 'John', 'last name': 'Doe', 'grade': '9', 'gpa': '4.0', 'school': {'name': 'Richard High School', 'city': 'Kansas City'}}}, 1: {'student': {'first name': 'Jane', 'last name': 'Doe', 'grade': '10', 'gpa': '3.0', 'school': {'name': 'Richard High School', 'city': 'Kansas City'}}}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456019.html
上一篇:如何列印字典中的所有內容?
