【问题标题】:Search and replace between two files with search phrase in first file: Python在第一个文件中使用搜索短语在两个文件之间搜索和替换:Python
【发布时间】:2014-11-28 03:41:10
【问题描述】:

文件 1:

$def String_to_be_searched (String to be replaced with)

文件 2:

..... { word { ${String to be searched} } # each line in File 2 is in this format
..... { word { ${String} } # This line need not be replaced. Only lines which matches the string in file 1 needs to be replaced

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

我的代码:

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这个作为参考。

【问题讨论】:

  • ${String to be searched} 是多个词还是一个词,因为您的正则表达式目前限制为 ${foo}
  • 所以它主要是一个词。喜欢:Foo 或 Foo_Bar ...
  • 你应该循环:for x in matches: print x
  • 好的,打印出匹配项。现在我如何只替换第一行中的那个字符串? line = line.replace(match, labelValues) 会起作用吗?
  • 除了被替换的字符串之外,您希望 file2 完全相同吗?

标签: python regex string match


【解决方案1】:

对于“第二部分” - 不需要正则表达式来替换 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

for search_txt, replacement_txt in Label.iteritems():
    data = re.sub(search_txt, replacement_txt, data)
print data

对于“第一部分” - 在 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

【讨论】:

  • 当我尝试在 for 循环中打印 searchtxt 和替换 txt 时,它不会打印出来。是否可以像您所做的那样调用 Label.iteritems()??
  • @Doodle 是的,请参阅教程中的Looping Techniques
  • 将标签创建为一个字典有帮助!非常感谢。
猜你喜欢
  • 2018-05-17
  • 2015-08-20
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2015-06-29
  • 2022-11-26
  • 2021-07-15
  • 1970-01-01
相关资源
最近更新 更多