2013-05-22 97 views
1

我有两个文件。一个用单词列表让我们说a.txt和另一个csv文件,其第二行是单词b.csv。我想检查a.txt中的任何单词是否在b.csv的第二行,并只打印那些不匹配的行。共有3行在csv文件中。从文件匹配单词列表并输出其余单词

我到目前为止所取得的成绩是打印那些从单词列表中有单词的行。但我想要的其他线路。这是我的代码:

reader = csv.reader(open('b.csv', 'rb')) 
op = open('a.txt', 'r') 
ol = op.readlines() 

for row in reader: 
    for word in ol: 
     if word==row[1]: 
      print row[0],row[1],row[2] 

现在我该如何使它打印不匹配的行? 谢谢!

回答

0

侵入性最小的解决方案(即保持你的嵌套循环)将沿

for row in reader: 
    match = False 
    for word in ol: 
     if word==row[1]: 
      match = True 
      break 

    if not match: 
     print row[0],row[1],row[2] 

或使用一些更Python的善良线的东西:

for row in reader: 
    for word in ol: 
     if word==row[1]: 
      break 
    else: 
     print row[0],row[1],row[2] 

else:位只执行前面的循环正常结束(没有达到break)。

至于建议的thg435,这是更简单:

for row in reader: 
    if row[1] not in ol: 
     print row[0],row[1],row[2] 
+0

谢谢。但是,我相当惊讶的是,“其他”是比原来的“如果”倒退的意图。这是平常的事吗?对我来说是新的。 –

+0

'else'属于第二个'for':http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops –

+0

I看到。从不知道这一点。确实美丽的教训。谢谢! :) –