简体   繁体   中英

How to check word in file with list element by using index?

I have a list of words in two files. I want to check the word from file 2 with file 1. The word that match will replace by 1. If have duplicate word then number of them will be count and used instead of 1. If not match then 0 will be used. They will used the same row format as in file 1. (sorry about my explanation)

file 1: a,b,c,1,5,9,12

file 2: a 1 c 12
        c 9 a b
        5 b 5 c
        9 12 a b 

I tried the code below but I still lost as I got all 0. Any suggestion?

        header = []
        for line in open(file1):
            lines = line.strip().split(',')
            for i,j in enumerate(lines):
                header.append(j)
            #print header
        for line in open(file2):
            linesMo = line.strip().split()
            for words in linesMo:
                if words != j:
                    print '0',
                if words == j:
                    print '1',

I want the results to be:

1, 0, 1, 1, 0, 0, 1     # a 1 c 12
1, 1, 1, 0, 0, 1, 0     # c 9 a b
0, 1, 1, 0, 2, 0, 0     # 5 b 5 c
1, 1, 0, 0, 0, 1, 1     # 9 12 a b 
with open("Input1.txt") as in_file1, open("Input2.txt") as in_file2:
    line = next(in_file1).rstrip().split(",")
    for row in map(str.split, in_file2):
        print [row.count(item) for item in line]

Output

[1, 0, 1, 1, 0, 0, 1]
[1, 1, 1, 0, 0, 1, 0]
[0, 1, 1, 0, 2, 0, 0]
[1, 1, 0, 0, 0, 1, 1]

You can do it even more efficiently, like this

from collections import Counter
with open("Input1.txt") as in_file1, open("Input2.txt") as in_file2:
    line = next(in_file1).rstrip().split(",")
    for row in map(str.split, in_file2):
        print map(Counter(row).__getitem__, line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM