开发者

Python 'in' Operator Inexplicably Failing

My simple script to check for a certain word in files seems to be failing, and I cannot seem to explain it through documentation or searching. The code is below. I believe I have narrowed it down to the 'in' operator failing by printing the code itself and finding the word that I am looking for. If curious, this script is to find certain keywords in the Quake source code, since I'd rather not look through 30+ full source files. A开发者_如何学JAVAny help would be appreciated, thanks!

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


The reason it is failing is because you are checking if the word is within the text's lines. Just use the read() method and check in there or iterate through all the lines and each each individually.

# 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)


text is a list of strings. That will return true if word is a line in text. You probably want to iterate through text, then check word against each lines. Of course, there are multiple ways to write that.

See this simple example.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜