python:使用要在txt-fi上搜索的关键字列表

2024-10-05 17:44:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我试图搜索一个txt文件,使用另一个txt文件中的关键字。 到目前为止,我的代码是这样的:

testfile=open('D:\\Coding\\testfile.txt')
keywordfile=open('D:\\Coding\\keyword.txt')

testfile.seek(0,0)
keywordfile.seek(0,0)
for keyword in keywordfile:
    print('\n****************\nlooking for: ', keyword)
    testfile.seek(0,0)
    for line in testfile:
            if keyword in line:
                print('keyword: ', keyword)
                print('line: ', line)

在关键字.txt包含以下内容:

^{pr2}$

以及测试文件.txt包含以下内容:

the quick 
brown fox jumps 
over the lazy dog
near the river banks

它应该在tesfile.txt文件然后打印出来,但是当我运行上面的代码时,我得到了以下结果:

****************
looking for:  quick


****************
looking for:  fox


****************
looking for:  jumps
keyword:  jumps
line:  brown fox jumps 

它找不到前两个关键字,而只找到最后一个关键字。在

我觉得这可能只是我的一个简单的错误,但我真的很感谢你的帮助,澄清我错在哪里。在

谢谢!在


Tags: 文件theintxtforlineseek关键字
3条回答

你可以这样做:

from itertools import cycle

with open('test_file','r') as tf, open('keyword_file', 'r') as kf:
    keywords = [k.strip() for k in kf]
    for lineno, line in enumerate(tf):
        for i, key in enumerate(cycle(keywords)):
            if i==len(keywords):
                break
            if key in line.strip():
                print "Keyword: '"+key+"' found on line: "+str(lineno)

输出:

^{pr2}$

我认为您在读取关键字时遇到问题,它可能还会在结尾包含\n或\t或\r字符或空格('')。你用的怎么样字符串。替换为了消除这种可能性:

 if keyword.replace(' ','').replace('\n','') in line:

或者你也可以用字符串.strip()在python中:

^{pr2}$

首先,我建议你读一次文件并将它们保存在内存中,这样你就不必每次都重读它们。可以使用Python的with语句,因此在处理之后不必关闭它们。在

with open("testfile.txt", "r") as f:
    testfile = f.readlines()

with open("keywords.txt", "r") as f: 
    keywords = f.readlines() 

然后,代码中的错误是文件中的行可能包含换行符\n或空格{}。Python有一个方便的函数来解决这个问题:strip()。以下是循环代码:

^{pr2}$

相关问题 更多 >