获取Python中匹配字符串的关键字

时间:2013-08-01 01:32:39

标签: python string text-files glob

我正在编写一个脚本,用于搜索目录中的文本文件以查找某些单词。如果返回“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 个答案:

答案 0 :(得分:0)

for line in f:
    for s in keywords:
         if s in line:
            print 'Key word found!', f.name, s   

答案 1 :(得分:0)

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

答案 2 :(得分:0)

另一种方法是使用:

for line in logfile:
    for word in line.split():
        if word in KEYWORDS:
            print word

答案 3 :(得分:0)

我认为对您的代码进行一些小修改就足够了

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