在python中获取搜索值上方的行
我有一个要搜索特定ip地址的文本文件,设置该文本文件的方式是主机名位于ip地址之上。即在python中获取搜索值上方的行,python,regex,sed,multiline,Python,Regex,Sed,Multiline,我有一个要搜索特定ip地址的文本文件,设置该文本文件的方式是主机名位于ip地址之上。即 real HOSTNAME address xx.xx.xx.xx 当我只获取要搜索的ip地址时,获取主机名的最佳/最简单方法是什么?正则表达式?python中是否有一个类似sed的实用程序具有保留空间?感谢您的帮助,正则表达式可能是最简单的解决方案 >>> textdata = ''' someline another line real HOSTNAME address 127.0
real HOSTNAME
address xx.xx.xx.xx
当我只获取要搜索的ip地址时,获取主机名的最佳/最简单方法是什么?正则表达式?python中是否有一个类似sed的实用程序具有保留空间?感谢您的帮助,正则表达式可能是最简单的解决方案
>>> 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']
您也可以使用或使用
f.readlines()
将所有行读取到列表中这可能不是最佳解决方案,但您可以使用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”)以从文本文件中读取行。如果您知道主机名在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
maxlen参数的良好使用:-)