在python中获取搜索值上方的行

2024-06-24 12:43:17 发布

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

我有一个文本文件,我想搜索特定的ip地址,文本文件的设置方式是主机名在ip地址之上。ie公司

real HOSTNAME

address xx.xx.xx.xx

当我只得到要搜索的ip地址时,获取主机名的最佳/最简单方法是什么?正则表达式?python中是否有类似sed的实用程序具有保留空间?谢谢你的帮助谢谢


Tags: 方法ip实用程序address地址方式公司real
3条回答

regex可能是最简单的解决方案。在

>>> textdata = '''
someline
another line
real HOSTNAME

address 127.0.0.1
post 1
post 2
'''
>>> re.findall('^(.*)$\n^.*$\naddress 127.0.0.1', textdata, re.MULTILINE)
['real HOSTNAME']

您也可以使用linecache module,或者简单地使用f.readlines()将所有行读入一个列表中。在

如果知道主机名在ip之前有多少行,则可以枚举一个行列表,并从当前索引中减去所需的行数:

lines = open("someFile", "r").read().splitlines()
IP = "10.10.1.10"
hostname = None
for i, line in enumerate(lines):
    if IP in line:
        hostname = lines[i - 1]
        break

if hostname:
    # Do stuff

这也许不是最好的解决方案,但您可以使用deque在目标线上方捕捉n条线:

from collections import deque
from itertools import takewhile

test = """
real others

address xxx.xxx.xxx

real local

address 127.0.0.1

real others

address xxx.xxx.xxx
""".split("\n")

pattern = "address 127.0.0.1"
print deque(takewhile(lambda x:x.strip()!=pattern, test), 2)[0]

将测试变量更改为file(“yourfilename”)以从文本文件中读取行。在

相关问题 更多 >