简体   繁体   English

使用python搜索和替换

[英]search and replace using python

I have the following file "template.txt" 我有以下文件“ template.txt”

function FA()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FB()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FC()
{
    if(){...}
    message=[msg]
    message=[msg]
}

I would like to do this: 我想这样做:

./script.py --function FB --message TEST

and get this result: 并得到以下结果:

function FA()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FB()
{
    if(){...}
    message=TEST
    message=TEST
}
function FC()
{
    if(){...}
    message=[msg]
    message=[msg]
}

I can now using getopt retrieve all the options and arguments properly but I can't figure out how to achieve the above behavior elegantly. 现在,我可以使用getopt正确检索所有选项和参数,但是我无法弄清楚如何优雅地实现上述行为。 Any ideas? 有任何想法吗? Are there any libraries that can help me with this? 有没有什么图书馆可以帮到我呢?

I was able to achieve this behavior using AWK but now I need it in python. 我能够使用AWK实现此行为,但是现在我需要在python中使用它。 In AWK you can go to a specific line (eg function FC()) and start replacing from there until you hit another function. 在AWK中,您可以转到特定的行(例如,函数FC())并从那里开始替换,直到您点击另一个函数。 I can't seem to figure this out in python. 我似乎无法在python中解决这个问题。

I am also wondering if there's a better approach to this problem. 我也想知道是否有更好的方法来解决此问题。

Once you get your variables, and have them sanitized properly you can do something like this. 一旦获得变量,并对其进行正确的清理,您可以执行以下操作。

def templater(template,function,message):
    template = template.split('function')
    for i,f in enumerate(template):
        if function in f:
            template[i] = f.replace('[msg]',message)
    return 'function'.join(template)

Edit: As far as a better approach, you should consider creating your template using the formatting mini language http://docs.python.org/2/library/string.html#formatspec or an actual templating language such as jinja2 http://jinja.pocoo.org/docs/ 编辑:就更好的方法而言,您应该考虑使用格式迷你语言http://docs.python.org/2/library/string.html#formatspec或实际的模板语言(例如jinja2 http:/)来创建模板/jinja.pocoo.org/docs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM