数据转换为数据结构

2024-03-28 15:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,我需要转换成一个列表。以下是数据表单文本文件:

'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"]]

有人能告诉我怎么转换这个吗?谢谢!你知道吗


Tags: theid列表on文本文件tricycleroyalepisode
2条回答

您也可以尝试regex方法:

>>> 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完全一样!你知道吗

因为每个项目都是由它的"ID="定义的,所以我使用这个术语来split()初始语句。你知道吗

然后就是在"\n"splitting每个句子的问题,操纵一些字符串并appending将它们转换成一个list称为results。你知道吗

代码:

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']

相关问题 更多 >