Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何从字符串中多次出现之间获取变量_Python_String_Variables - Fatal编程技术网

Python如何从字符串中多次出现之间获取变量

Python如何从字符串中多次出现之间获取变量,python,string,variables,Python,String,Variables,假设我有一个输入文件(temp.tmpl),如下所示: PTF @ ARB @ C @ @ A @ @ C @ OSN @ B @ @ A @ SDA @ B @ CPN 3.23 SNL 3.26 在其他一些文件(candidate.txt)中: 我想用它们的赋值来代替A,B和C。 我的任务需要通过找到 变量A、B和C,通过查找@…,然后知道这显然是一个变量。 然后更换它们。这就是我尝试过的: reader = open('candidate.txt', 'r') out = open(

假设我有一个输入文件(temp.tmpl),如下所示:

PTF @
ARB @ C @ @ A @ @ C @
OSN @ B @ @ A @ 
SDA @ B @
CPN 3.23
SNL 3.26 
在其他一些文件(candidate.txt)中:

我想用它们的赋值来代替A,B和C。 我的任务需要通过找到 变量A、B和C,通过查找@…,然后知道这显然是一个变量。 然后更换它们。这就是我尝试过的:

reader = open('candidate.txt', 'r')
out = open('output.txt', 'w')

dictionary = dict()
for line in reader.readlines():
    pairs = line.split()
    for variable, value in zip(pairs[::2],pairs[1::2]):
        dictionary[variable] = value

#Now to open the template file
template = open('temp.tmpl', 'r')
for line1 in template:
    if line1[1]:
        confirm = line1.split(' ')[0].lower()
        symbol = line1.split(' ')[1]

        if confirm == 'ptf':
            next(template)

        elif symbol in line1:

            start = line1.find(symbol)+len(symbol)
            end = line1[start:].find(symbol)
            variable = line1[start:start + end].strip()
            print variable
而且我似乎不知道如何处理带有多组变量的行。

提前非常感谢。

简单的字符串替换不适合您吗

>>> 'foo @ A @ @ B @'.replace('@ A @','12345')
'foo 12345 @ B @'
它将把所有出现的
@A@
替换为您想要的内容。您可以多次应用它,可能对每个变量应用一次:

# a dictionary of variable values,
# you'll probably read this from somewhere
values = { 'A': '123', 'B': '456' }

# iterate over variable names
for varname in values: 
    pattern = str.format('@ {} @', varname)
    value = values[varname]

    # data is your input string
    data = data.replace(pattern, value)

使用re?问题被修改了,下面是我修改后的解决方案:

import re

# Create translation dictionary
codes = re.split(r'\s',open('candidate.txt').read())
trans = dict(zip(codes[::2], codes[1::2]))

outfh = open('out.txt','w')
infh  = open('data.txt')

# First line contains the symbol, but has a trailing space!
symbol = re.sub(r'PTF (.).*',r'\1', infh.readline()[:-1])

for line in infh:
    line = re.sub('\\'+ symbol + r' ([ABC]) ' + '\\' + symbol,
               lambda m: '%s %s %s' % (symbol,trans[m.groups()[0]],symbol),
               line)
    outfh.write(line) 

outfh.close()
使用两个
zip
s的
dict
是一个从[key,value,key,value,…]列表创建字典的技巧

trans
是一本包含名称及其各自值的词典。
r'@([ABC])@
捕获@符号中的A、B或C
lambda
函数被传递一个匹配对象,我们在该对象上调用
groups()
方法。这将返回匹配括号组的元组,在本例中为a、B或C。我们将其用作字典
trans
的键,因此,将其替换为值。

看起来正则表达式在这种情况下很有用。您是否尝试将正则表达式与
re.sub一起使用?请记住关闭文件句柄。感谢您的帖子,因为它确实很有帮助,我现在正在学习re的一些知识,但是如果从输入文件的第一行开始,@被定义为symbol,而现在代码中的所有地方,@都被变量“symbol”替换,那么语法会发生怎样的变化?这仍然有效吗?是的,前提是该符号不是像*或那样的重元字符(特殊字符)。或[或{或+或?等等。如果有疑问,请在其左侧放置一个\号。如果符号包含在变量中,这也适用。嗯……让我编辑我的原始帖子,以包含我想做的一切。进一步考虑,环顾四周可以简化lambda(但使re更复杂)
import re

# Create translation dictionary
codes = re.split(r'\s',open('candidate.txt').read())
trans = dict(zip(codes[::2], codes[1::2]))

outfh = open('out.txt','w')
infh  = open('data.txt')

# First line contains the symbol, but has a trailing space!
symbol = re.sub(r'PTF (.).*',r'\1', infh.readline()[:-1])

for line in infh:
    line = re.sub('\\'+ symbol + r' ([ABC]) ' + '\\' + symbol,
               lambda m: '%s %s %s' % (symbol,trans[m.groups()[0]],symbol),
               line)
    outfh.write(line) 

outfh.close()