如何使用索引检查文件中的单词元素?

时间:2014-05-02 16:11:53

标签: python python-2.7

我有两个文件中的单词列表。我想用文件1检查文件2中的单词。匹配的单词将替换为1.如果有重复的单词,则它们的数量将被计数并使用而不是1.如果不匹配则将使用0。它们将使用与文件1中相同的行格式。 (对不起我的解释)

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 

我尝试了下面的代码,但是当我得到全部0时我仍然输了。任何建议?

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

我希望结果为:

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 

1 个答案:

答案 0 :(得分:0)

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]

<强>输出

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

你可以更有效地完成这项工作,比如

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)