0

我正在编写一个脚本,该脚本在目录中的文本文件中搜索某些单词。如果返回“True”,那么它将打印找到它的文本文件。有没有办法返回/打印它实际​​找到的关键字?谢谢!

from glob import glob

def main():
    directory = "C:\\Files Folder\\*.txt"
    filelist = glob(directory)
    keywords = ("Hello", "Goodbye", "fake")
    for textfile in filelist:
        f = open(textfile, 'r')
        for line in f:
            if any(s in line for s in keywords):
                print "Keyword Found!", f.name

if __name__ == '__main__':
    main()
4

4 回答 4

0
for line in f:
    for s in keywords:
         if s in line:
            print 'Key word found!', f.name, s   
于 2013-08-01T01:36:36.703 回答
0

不是这样。您必须将any()调用扩展为for循环才能找到找到的特定关键字。

于 2013-08-01T01:36:52.007 回答
0

An alternative way is to use:

for line in logfile:
    for word in line.split():
        if word in KEYWORDS:
            print word
于 2013-08-01T01:39:27.837 回答
0

I think a small modification of you code is enough

from glob import glob

def main():
    directory = "C:\\Files Folder\\*.txt"
    filelist = glob(directory)
    keywords = ("Hello", "Goodbye", "fake")
    for textfile in filelist:
        f = open(textfile, 'r')
        for line in f:
            for keyword in keywords:
                if line.find(keyword)>0 :
                    print "Keyword Found!",keyword, f.name

if __name__ == '__main__':
    main()
于 2013-08-01T01:42:54.287 回答