姓名年龄等级
雅各布10 60
约翰11 75
马特13 81
如果以上是记事本中的文本文件,我如何将其转换为以下形式的字典:
{'Jacob':{ 'Age': '10', 'Grade': 60}, 'John':{'Age': '11', 'Grade': 75}, 'Matt': {'Age': '13', 'Grade': 81}}
在python中?
答案 0 :(得分:0)
使用正则表达式组的解决方案
import re
# Read File into variable
file = "Name Age Grade Jacob 10 60 John 11 75 Matt 13 81"
# Match Name, age, Grade
pattern = re.compile(r'([A-z]+)\s([0-9]+)\s([0-9]+)')
# Create Dictionary Placeholder
dictionary = {}
# For each match split groups into separate vars
for name, age, grade in re.findall(pattern, file):
# Add To Dictionary
dictionary[name] = {
'Age':age,
'Grade':grade
}
print(dictionary)
输出
{'Jacob': {'Age': '10', 'Grade': '60'}, 'John': {'Age': '11', 'Grade': '75'}, 'Matt': {'Age': '13', 'Grade': '81'}}
将文本读入变量
file = open('textdocument.txt', 'r').read()
答案 1 :(得分:0)
您可能缺少的部分是基于空格的行分割。
data = {}
with open('textfile') as fh:
for line in fh:
name, age, grade = line.split()
data[name] = { 'age': age, 'grade': grade}