1

i want to only display the second column ,

this is my code

with open('try.txt', 'rb') as file1:
    file1_data = dict(line.split(None, 2)[1:] for line in file1 if line.strip())
print file1_data

I only want to display the second column , but its also diplaying 3rd with it

This is the text file

E5 BAT One 
E5 BALL Two 
E5 CRICKET Three 

Than i have to find the Bat which is in second column of textfile1 in second text file

    ?Bat03|Batsman
    This is the goods of cricket
    ?Balt|Bowler
    Both can be use by batsman and bowler
    ?Bat133|Swimmer
    Swiming is the best exercise

So the Bat which is in second column of textfile1 we goto second text file and find Bat and ignore value after | , if Bat in second text file before | found than display it

with open('second.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
    output = csv.writer(outputfile, delimiter='|')
    for line in file2:
        if line[:1] == '?':
            row = line.strip().split('|')
            key = row[0][1:]
            if key in file1_data:
                output.writerow(row + [file1_data])
        else:
            outputfile.write(line)

Required output

?Bat03|Batsman
        This is the goods of cricket
?Bat133|Swimmer
        Swiming is the best exercise
4

1 回答 1

3

为什么不只是在拆分后索引行?

line.split()[1]

代替:

line.split(None,2)[1:]

当然,这对字典也不满意。我不确定你为什么在那里有一个字典。如果对您来说都一样,我建议您改用 a list

file1_data = [line.split()[1] for line in file1 if line.strip()]

如果你真的想保留字典,那么你几乎已经得到了你想要的。可以构造第一列,file1_data.keys()从中返回一个可迭代对象(在 python2.x 上它是一个列表,在 python3.x 上它是一个类似集合的对象)。当然,由于这是一本字典,原始文件中的所有顺序都会丢失。

于 2013-05-10T12:43:20.203 回答