根据另一部分替换字符串的一部分

时间:2014-09-17 03:42:14

标签: python

我有一系列通过文本文件给出的字符串

strings.txt:

printing "This is not easy!"
John Roberts and Judiciary
printing "valid hello"      $ printing "comment" 
printing "abc",

这些内容将是输入。输出必须如下所示,

printing("This is not easy!")
John Roberts and Judiciary
printing("valid hello")      $ printing "comment" 
printing ("abc", shell=" ") 

在这里,每当我们看到打印时,它应该在两端添加()。但如果打印在$之后,则不应该放()。它应该是孤立的。如果打印结尾有逗号,那么打印应该包含逗号,之后应该有shell =" " 。

完全感谢我使用了这个:Replacing strings line by line

def main():
    with open('string.txt', 'r') as fileopening:
        next(fileopening)
        for line in fileopening:
            if 'printing' in line:
                print '{}({})'.format(line[:9], line[9:])

但它只显示:

printing("This is not easy!")
John Roberts and Judiciary
printing("valid hello")      $ printing("comment")

如何实现?

1 个答案:

答案 0 :(得分:1)

你需要的只是一些逻辑。这对你有用。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

def main():
    with open('C:\\Temp\\001.txt', 'r') as fileopening, \
    open('C:\\Temp\\002.txt', 'w') as fileTarget:
        for line in fileopening:
            if 'printing' in line and '$' not in line:
                lineInfo = line.split('"')
                lineInfo[0] += '("'
                if line.endswith(','):
                    lineInfo[-2] += '", '
                    lineInfo[-1] = 'shell=" ")'
                else:
                    lineInfo[-2] += '")'
                line = ''.join(lineInfo)

            elif 'printing' in line and '$' in line:
                lineInfo = line.split('"')
                lineInfo[0] += '("'
                lineInfo[1] += '")'
                lineInfo[-2] = '"'+lineInfo[-2]+'"'
                line = ''.join(lineInfo)    
            fileTarget.write(line)

main()