0

所以有一个输入文件到脚本,如下所示:

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)

任何帮助都会很棒。

4

2 回答 2

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]})
于 2012-12-20T12:58:19.300 回答
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
于 2012-12-20T12:57:03.683 回答