2017-04-03 84 views
1

我有一個文本文件,我需要將其轉換爲列表。這裏的數據格式的文本文件:數據轉換爲數據結構

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

是否有人可以讓我知道如何轉換這樣的列表的形式?非常感謝!

+0

你想要的結果是什麼? – zondo

+0

@zondo我想要的結果是打印一個列表L(見上面的輸出),我剛剛從文本文件 – Sophie

+2

中加入了原始數據那不是字典;這是一個列表。那是你要的嗎? – zondo

回答

2

由於每個項目都是由其"ID="定義的,所以我用這個術語split()開頭的句子。

當時,只是splitting每個句子的事在"\n",操縱弦數appending他們一個叫resultslist

代碼:

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

1

您也可以嘗試正則表達式的方法:

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