gpt4 book ai didi

python 在文本文件中搜索字符串并将值添加到变量中

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:07 25 4
gpt4 key购买 nike

我有一个这样的文本文件

PC Name : Sarah , IP : x.x.x.x
ID : AC:AC LP
PC Name : Moh, IP : x.x.x.x
ID : AC:AC LP

我想“从文件末尾向上”搜索以查找字符串“AC:AC LP”的第一个匹配项然后我想复制上一行中的 ip 并将其添加到名为 ip 的新变量中

我搜索了代码,但它们都使用正常搜索并复制相同的字符串,您能帮忙吗

最佳答案

with open(in_file) as f:
lines = reversed(f.readlines()) # start from end of file
for line in lines:
if "AC:AC LP" in line: # if AC:AC LP is in the line
print( next(lines).rsplit(":",1)[-1]) # go to next line, split, get ip and break the loop
break

在函数中:

def find_ip(in_file,sub_s):
with open(in_file) as f:
lines = reversed(f.readlines())
for line in lines:
if sub_s in line:
return next(lines).rsplit(":", 1)[-1]

如果 ip 并不总是最后一个元素,请使用 re:

def find_ip(in_file,sub_s):
import re
with open(in_file) as f:
lines = reversed(f.readlines())
for line in lines:
if sub_s in line:
return re.findall(r"[0-9]+(?:\.[0-9]+){3}",next(lines))[0]

关于python 在文本文件中搜索字符串并将值添加到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com