python - 在一个文本文件中搜索另一个文本文件的值,然后打印该行

标签 python python-2.7 python-3.x

我正在寻找一些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/

相关文章:

python - EOF 发生违反 Python ftplib 协议(protocol)

python - 无法通过 pip 安装数据集包

python - python 库的嵌套字典与 JSON 文件

python - 在 pyGraphViz 中设置节点的颜色

Python Fabric 给出 : Fatal error: No existing session

python - 将列表中的每个元素与所有其他元素进行比较

python - 将时间转换为纪元(Python)

python - 通过递归生成元素列表

python-3.x - numpy.loadtxt 无法在 Python 3 中读取 int

python - 如何使子图的大小相等?