搜索和替换两个文件中第一个文件中的搜索短语:Python

2024-09-30 08:37:56 发布

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

文件1:

$def String_to_be_searched (String to be replaced with)

文件2:

^{pr2}$

我想将文件2中的“要搜索的字符串”替换为文件1中的“要替换的字符串”,只要文件2中的每一行都有“要搜索的字符串”。在

我的代码:

def labelVal(line):
    return line[line.find('(') + 1: line.rfind(')')]

for line in File 1:
    Label = {}
    line = line.strip()
    if line.startswith('$def'):
        labelKeys = line .split()[1]
        #print labelKeys
        labelValues = labelVal(line)
        #print labelValues
        Label[labelKeys] = labelValues
        #print Label
outfile = open('path to file','w')

for line in File 2:
    match = re.findall(r'\$\{(\w+)\}', line) # Here I am searching for the pattern ${String to be searched}
    if match:
        print match.group()

目前产量:

我有一个字典的标签,有要搜索的字符串和要替换的字符串。我首先尝试匹配两个文件中的字符串,然后我必须替换。但第二部分没有给我任何匹配。。。我用compare two file and find matching words in python这个作为参考。在


Tags: 文件to字符串inforstringdefmatch
1条回答
网友
1楼 · 发布于 2024-09-30 08:37:56

对于“第二部分”,不需要正则表达式来替换File 2中的文本。只需读取整个文件并使用str方法replace。在

with open('tobefixed.txt') as f:
    data = f.read()

for search_txt, replacement_txt in Label.iteritems():
    data = data.replace(search_txt, replacement_txt)

with open('fixed.txt', 'w') as f:
    f.write(data)

如果要使用re模块,请使用re.sub

^{pr2}$

对于“第一部分”—在for循环的每次迭代中创建一个新字典Label。您只需创建一个包含所有defs的字典

with open('defs.txt') as f:
    Label = {}
    for line in f:
        line = line.strip()
        if line.startswith('$def'):
            labelKeys = line .split()[1]
            labelValues = labelVal(line)
            Label[labelKeys] = labelValues

相关问题 更多 >

    热门问题