2011-10-02 91 views
0

我的简单脚本检查文件中的某个单词似乎失败了,我似乎无法通过文档或搜索来解释它。代码如下。我相信我通过打印代码本身并找到我正在寻找的单词来缩小它到'in'操作符的范围。如果好奇,这个脚本是在Quake源代码中查找某些关键字,因为我不想查看30个以上完整的源文件。任何帮助将不胜感激,谢谢!Python'in'运算符无法解释失败

import os 

def searchFile(fileName, word): 
    file = open(os.getcwd() + "\\" + fileName,'r') 
    text = file.readlines() 

    #Debug Code 
    print text 

    if(word in text): 
     print 'Yep!' 
    else: 
     print 'Nope!' 
+4

无关的,但是你的括号是不必要的。这样做更“pythonic”:“如果文字中有文字:' –

+1

附注:描述某种莫名其妙的失败可能会引起人们的注意。它更像是你误解了某些东西。 –

回答

7

它失败的原因是因为您正在检查单词是否在文本的行内。只需使用read()方法并在那里检查或遍历所有行,并分别单独执行。

# first method 
text = file.read() 

if word in text: 
    print "Yep!" 

# second method 
# goes through each line of the text checking 
# more useful if you want to know where the line is 

for i, line in enumerate(file): 
    if word in line: 
     print "Yep! Found %s on line: %s"%(word, i+1) 
+8

使用'enumerate(file,1)';那么你可以使用'i'而不是'i + 1'。 –

+0

+1因为我没有把2 + 2放在一起,你可以在File实例上使用枚举,这很愚蠢,因为我之前已经为myFile中的行完成了。 – David

5

text是一个字符串列表。如果wordtext,则返回true。你可能想通过文字iterate,然后检查每一行的单词。当然,有多种方式可以编写它。

看到这个simple example

0
for line_num, line in enumerate(file, 1): 
    if word in line: 
     print line_num, line.strip() 
+1

和downvote是为了什么? –