python 字符串转变量_在python中将字符串的一部分转换为变量名

该博客介绍了如何使用Python正则表达式从给定的配置文件中提取应用程序列表(如application1和application2)及其对应的服务器地址。通过逐行解析和匹配模式,作者提供了两种不同的方法来创建字典结构存储数据。
摘要由CSDN通过智能技术生成

问题

我有一个包含如下文本的文件:

loadbalancer {

upstream application1 {

server 127.0.0.1:8082;

server 127.0.0.1:8083;

server 127.0.0.1:8084;

}

upstream application2 {

server 127.0.0.1:8092;

server 127.0.0.1:8093;

server 127.0.0.1:8094;

}

}

有谁知道,我怎么能提取如下变量:

appList=["application1","application2"]

ServerOfapp1=["127.0.0.1:8082","127.0.0.1:8083","127.0.0.1:8084"]

ServerOfapp2=["127.0.0.1:8092","127.0.0.1:8093","127.0.0.1:8094"]

等等

python

regex

server

回答

如果您想要的行总是从上游和服务器开始,这应该工作:

app_dic = {}

with open('file.txt','r') as f:

for line in f:

if line.startswith('upstream'):

app_i = line.split()[1]

server_of_app_i = []

for line in f:

if not line.startswith('server'):

break

server_of_app_i.append(line.split()[1][:-1])

app_dic[app_i] = server_of_app_i

app_dic应该是列表的字典:

{'application1': ['127.0.0.1:8082', '127.0.0.1:8083', '127.0.0.1:8084'],

'application2': ['127.0.0.1:8092', '127.0.0.1:8093', '127.0.0.1:8094']}

编辑

如果输入文件不包含任何换行符,只要文件不是太大,您就可以将其写入列表并迭代它:

app_dic = {}

with open('file.txt','r') as f:

txt_iter = iter(f.read().split()) #iterator of list

for word in txt_iter:

if word == 'upstream':

app_i = next(txt_iter)

server_of_app_i=[]

for word in txt_iter:

if word == 'server':

server_of_app_i.append(next(txt_iter)[:-1])

elif word == '}':

break

app_dic[app_i] = server_of_app_i

这更难看,因为必须搜索结束的花括号才能打破。 如果它变得更复杂,应该使用正则表达式。

回答

如果您能够使用Matthew Barnett的新版regex模块 ,您可以使用以下解决方案,请参阅regex101.com上的其他演示 :

import regex as re

rx = re.compile(r"""

(?:(?Papplication\d)\s{\n| # "application" + digit + { + newline

(?!\A)\G\n) # assert that the next match starts here

server\s # match "server"

(?P[\d.:]+); # followed by digits, . and :

""", re.VERBOSE)

string = """

loadbalancer {

upstream application1 {

server 127.0.0.1:8082;

server 127.0.0.1:8083;

server 127.0.0.1:8084;

}

upstream application2 {

server 127.0.0.1:8092;

server 127.0.0.1:8093;

server 127.0.0.1:8094;

}

}

"""

result = {}

for match in rx.finditer(string):

if match.group('application'):

current = match.group('application')

result[current] = list()

if current:

result[current].append(match.group('server'))

print result

# {'application2': ['127.0.0.1:8092', '127.0.0.1:8093', '127.0.0.1:8094'], 'application1': ['127.0.0.1:8082', '127.0.0.1:8083', '127.0.0.1:8084']}

这使用了\\G修饰符,命名捕获组和一些编程逻辑。

回答

这是基本方法:

# each of your objects here

objText = "xyz xcyz 244.233.233.2:123"

listOfAll = re.findall(r"/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):[0-9]{1,5}/g", objText)

for eachMatch in listOfAll:

print "Here's one!" % eachMatch

显然,边缘有点粗糙,但它会对它给出的任何字符串执行全面的正则表达式搜索。 可能更好的解决方案是将对象本身传递给它,但是现在我不确定你将拥有什么作为原始输入。 不过,我会尝试改进正则表达式。

回答

我相信这也可以得到解决re :

>>> import re

>>> from collections import defaultdict

>>>

>>> APP = r'\b(?Papplication\d+)\b'

>>> IP = r'server\s+(?P[\d\.:]+);'

>>>

>>> pat = re.compile('|'.join([APP, IP]))

>>>

>>>

>>> scan = pat.scanner(s)

>>> d = defaultdict(list)

>>>

>>> for m in iter(scan.search, None):

group = m.lastgroup

if group == 'APP':

keygroup = m.group(group)

continue

else:

d[keygroup].append(m.group(group))

>>> d

defaultdict(, {'application1': ['127.0.0.1:8082', '127.0.0.1:8083', '127.0.0.1:8084'], 'application2': ['127.0.0.1:8092', '127.0.0.1:8093', '127.0.0.1:8094']})

或者与re.finditer方法类似,没有pat.scanner :

>>> for m in re.finditer(pat, s):

group = m.lastgroup

if group == 'APP':

keygroup = m.group(group)

continue

else:

d[keygroup].append(m.group(group))

>>> d

defaultdict(, {'application1': ['127.0.0.1:8082', '127.0.0.1:8083', '127.0.0.1:8084'], 'application2': ['127.0.0.1:8092', '127.0.0.1:8093', '127.0.0.1:8094']})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值