数据.txt:
name: hello_world
rating: 5
description: basic program
name: python
rating: 10
description: programming language
代码:
import pandas as pd
with open('data.txt', 'rt') as fin:
lst = [line[:-1] for line in fin if line[:-1]]
print(lst)
# Soln 1
d = dict()
d['name'] = [ele.split(':')[1] for ele in lst if ele.startswith('name:')]
d['rating'] = [ele.split(':')[1] for ele in lst if ele.startswith('rating:')]
d['description'] = [ele.split(':')[1] for ele in lst if ele.startswith('description:')]
df = pd.DataFrame(data=d)
print(df)
#或者
data_tuples_lst = [(lst[i].split(':')[1], lst[i+1].split(':')[1], lst[i+2].split(':')[1]) for i in range(0, len(lst), 3) ]
df1 = pd.DataFrame(data=data_tuples_lst, columns = ['name', 'rating', 'description'])
print(df1)
输出:
['name: hello_world', 'rating: 5', 'description: basic program', 'name: python', 'rating: 10', 'description: programming language']
name rating description
0 hello_world 5 basic program
1 python 10 programming language
name rating description
0 hello_world 5 basic program
1 python 10 programming language