数据转换为数据结构
问题描述:
我有一个文本文件,我需要将其转换为列表。这里的数据格式的文本文件:数据转换为数据结构
'ID=s4k5jk\nDate=8 December 1970\nTitle=crossing the atlantic on a tricycle\nID=f983\nDate=22 December 1970\nTitle=Royal Episode 13'
我需要的输出看起来像这样
l = [
#ID Date Title
["s4k5jk", "8 December 1970", "crossing the atlantic on a tricycle"],
["f983", "22 December 1970", "Royal Episode 13"]]
是否有人可以让我知道如何转换这样的列表的形式?非常感谢!
答
由于每个项目都是由其"ID="
定义的,所以我用这个术语split()
开头的句子。
当时,只是splitting
每个句子的事在"\n"
,操纵弦数appending
他们一个叫results
list
。
代码:
s = 'ID=s4k5jk\nDate=8 December 1970\nTitle=crossing the atlantic on a tricycle\nID=f983\nDate=22 December 1970\nTitle=Royal Episode 13'
data = s.split("\nID=")
results = []
for d in data:
res = d.split("\n")
_id = res[0].replace("ID=", "")
_date = res[1].replace("Date=", "")
_title = res[2].replace("Title=", "")
results.append([_id, _date, _title])
for r in results:
print(r)
输出:
['s4k5jk', '8 December 1970', 'crossing the atlantic on a tricycle']
['f983', '22 December 1970', 'Royal Episode 13']
+0
data = s.split(“ID =”)更好,因为它允许将第一个条目也考虑在内。 但是在这个版本的解决方案中,从“for data in [1:]” – wave5459
答
您也可以尝试正则表达式的方法:
>>> print(s)
ID=s4k5jk
Date=8 December 1970
Title=crossing the atlantic on a tricycle
ID=f983
Date=22 December 1970
Title=Royal Episode 13
>>> fields = re.findall(r'ID=([\s\S]+?)\sDate=([\s\S]+?)\sTitle=([\s\S]+?)$', s, re.MULTILINE)
>>> fields
[('s4k5jk', '8 December 1970', 'crossing the atlantic on a tricycle'), ('f983', '22 December 1970', 'Royal Episode 13')]
>>>
注意,使用捕获组作品完全一样一个会希望re.findall
!
你想要的结果是什么? – zondo
@zondo我想要的结果是打印一个列表L(见上面的输出),我刚刚从文本文件 – Sophie
中加入了原始数据那不是字典;这是一个列表。那是你要的吗? – zondo