我正在寻找一些Python代码,这些代码将从textfile1.txt中获取值,然后搜索textfile2.txt中的每一行并返回包含textfile1.txt中的值的任何行。举个例子:
textfile1.text contains:
Chad
Flash
Arrow
textfile2.text contains:
Who is awesome? Chad
Fastest human alive? Flash
Looks good in green? Arrow
一旦找到 textfile1 中的内容,我就需要它来打印 textfile2 中的前一行代码。根据此特定数据库的设置方式,textfile1 中的值将始终出现在 textfile2 中的行末尾。我尝试了很多方法,但就是无法让它发挥作用。这是我得到的最接近的任何结果:
with open("textfile2.txt") as f:
x = f.read()
with open("textfile1.txt") as f:
for i in (line.strip() for line in f):
if i in x:
print(i, ', found.')
结果如下:
[Chad] , found.
[Flash] , found.
[Arrow] , found.
我尝试翻转textfile1和textfile2但无济于事。任何帮助将不胜感激!我什至不确定这是否可以做,但我想在放弃之前我应该在这里问一下。
最佳答案
您还需要打印该行:
with open('textfile2.txt') as f:
words = [line.strip() for line in f]
with open('textfile1.txt') as f:
for line in f:
if line.split(' ')[-1].strip() in words:
print(line)
我将每一行分成一个空格,作为获取所有单词的廉价方式:
>>> s = 'Who is awesome? Chad'
>>> s.split(' ')[-1]
'Chad'
关于python - 在一个文本文件中搜索另一个文本文件的值,然后打印该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27895843/