在一个文本文件中搜索另一个文本文件的值,然后打印该行
Search one text file for values of another and then print that line
我正在寻找一些 python 代码,这些代码将从 textfile1.txt 中获取值,然后在 textfile2.txt 和 return 任何包含该值的 LINE 中搜索每一行来自 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 中行的末尾。我已经尝试了很多东西,但我就是无法让它工作。这是我最接近获得 any 结果的时间:
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)
我将每一行拆分为 space,作为获取所有单词的廉价方式:
>>> s = 'Who is awesome? Chad'
>>> s.split(' ')[-1]
'Chad'
打印行而不是 print (i)
;
print(line, ', found.')
因为i
是这里的单词,所以你要打印行,而不是单词。
我正在寻找一些 python 代码,这些代码将从 textfile1.txt 中获取值,然后在 textfile2.txt 和 return 任何包含该值的 LINE 中搜索每一行来自 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 中行的末尾。我已经尝试了很多东西,但我就是无法让它工作。这是我最接近获得 any 结果的时间:
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)
我将每一行拆分为 space,作为获取所有单词的廉价方式:
>>> s = 'Who is awesome? Chad'
>>> s.split(' ')[-1]
'Chad'
打印行而不是 print (i)
;
print(line, ', found.')
因为i
是这里的单词,所以你要打印行,而不是单词。