我是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
它找不到前两个关键字,而只找到最后一个关键字。在
我觉得这可能只是我的一个简单的错误,但我真的很感谢你的帮助,澄清我错在哪里。在
谢谢!在
你可以这样做:
输出:
^{pr2}$我认为您在读取关键字时遇到问题,它可能还会在结尾包含\n或\t或\r字符或空格('')。你用的怎么样字符串。替换为了消除这种可能性:
或者你也可以用字符串.strip()在python中:
^{pr2}$首先,我建议你读一次文件并将它们保存在内存中,这样你就不必每次都重读它们。可以使用Python的with语句,因此在处理之后不必关闭它们。在
然后,代码中的错误是文件中的行可能包含换行符}。Python有一个方便的函数来解决这个问题:
^{pr2}$\n
或空格{strip()
。以下是循环代码:相关问题 更多 >
编程相关推荐