2012-12-20 119 views
0

行,以便有一個輸入文件腳本像如下:使用Python來提取包含不同的關鍵字進入詞典

20248109|Generic|1|xxx|2|yyy|LINEA|68.66|68.67|True|2920958141272 
. 
. 
. 
21248109|Generic|3|xxx|4|www|LINEB|7618|7622|True|2920958281071.97 

希望python腳本來遍歷並把LINEA到字典中類似如下{{1:[68.66,68.67]},{3:[7618,7622]}}

這裏的,據我已經得到了:

Key = ["LINEA", "LINEB"] 
fin = open(path) 
test = [] 
for line in fin.readlines(): 
    if True in [item in line for item in Key]: 
     test.append(line) 

任何幫助都將是非常美妙。

+0

-1因爲你不知道True和'True'之間的不同, –

回答

1

我這樣做:

keys = ["LINEA", "LINEB"] 
with open(path) as fin 
    answer = {line.partition("Generic|")[-1]:line for line in fin if any(key in line for key in keys)} 

要直接編輯你的答案,你實際上是相當接近:

Key = ["LINEA", "LINEB"] 
fin = open(path) 
test = {} # dictionary 
for line in fin.readlines(): 
    if True in [item in line for item in Key]: 
     dict_key = line.partition("Generic|")[-1] 
     test[dict_key] = line 
+2

在這裏最好使用'with'結構。 – cmh

+0

感謝您的幫助 – user1862895

3

首先,你應該使用csv模塊:

import csv 
with open(path, "rb") as infile: 
    reader = csv.reader(infile, delimiter="|") 

然後,您可以遍歷行:

test = [] 
for row in reader: 
    if row[6] in Key: 
     test.append({int(row[2]): row[7:9]}) 
+0

當我嘗試這個,行超出範圍(行[6]) – user1862895

+0

在您的測試數據上,行包含11列,例如'row [6]'包含'LINEA'。如果您的實際數據看起來不像您提供的示例,則需要編輯您的問題以反映該問題。 –