Python:将字符串替换为文件中的变量

时间:2017-02-18 14:56:07

标签: python

如果我有这样的文件内容:

old_string
-old_string

我只想更改" old_string"成为" + new_string"所以结果看起来像

+new_string
-old_string

我的代码给出了这个结果:

+new_string
-+new_string

这是我的代码:

    with open(filename) as f:

    s = f.read()

    if old_string not in s:

        return False

with open(filename, 'w') as f:

    s = s.replace(old_string, new_string)

    f.write(s)

    return True

我试过正则表达式,但由于我将正则表达式作为变量传递,它不会起作用,这是我到目前为止所做的:

    with open (filename, 'r' ) as f:

       content = f.read()

content_new = re.sub('(\%old_string)', r'\new_string'%(old_string,new_string), content, flags = re.M)      

4 个答案:

答案 0 :(得分:1)

语法有点偏;你可能想要做更像这样的事情:

import re

test_str = ("old_string\n"
            "-old_string")

match = "old_string"
subst = "+new_string"

regex = r"^{}".format(match)

# You can manually specify the number of replacements by changing
# the 4th argument

result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix 
# the regex and u"" to prefix the test string and substitution. 

模式中的^断言是我建议使用的,因为它表示要匹配的字符串应该从行的最开头开始,因此不匹配-old_string

答案 1 :(得分:1)

你可以忽略开头有连字符(" - ")的行,然后替换其余的。

以下脚本与您的脚本略有不同。我已提出意见以帮助您理解。这应该很容易理解。

filename ="some_file"
output_filename = "some_other_file"

old_string = "old_string"
new_string = "+new_string"

input_file_handle = open(filename,"r") # File being opened in read mode
output_file_handle = open(output_filename, "w") # File being opened in write mode

# Read in input file line by line
for line in input_file_handle:

    # Write to output file and move on to next line
    if old_string not in line:
        output_file_handle.write(line+"\n")
        continue

    # This line contains the old_string. We check if it starts with "-". 
    # If it does, write original line and move on to next line
    if line.startswith("-"):
        output_file_handle.write(line+"\n")
        continue


    # At this stage we are absolutely sure we want to replace this line's contents
    # So we write the replaced version to the new file
    output_file_handle.write(new_string+"\n")


# Close both file handles
input_file_handle.close()
output_file_handle.close()

答案 2 :(得分:1)

我的解决方案的一个好处是它不依赖于行的开头的“do-not-replace”前缀。

如果你想在没有正则表达式的情况下解决这个问题,你可以编写自己的替换方法:

replace.txt

old_string
-old_string

old_string -old_string --old_string old_string

replace.py

import sys
import fileinput

def replace_exclude(string, search, replace="", excluding_char='-'):
    # Does replace unless instance in search string is prefixed with excluding_char.
    if (not string) or (not search): return None
    for i in range(len(string)):
        while string[i-1] == excluding_char:
            i += 1
        if i < len(string):
            for j in range(len(search)):
                possible = True
                if not (string[i + j] == search[j]):
                    possible = False
                    break
        if possible:
            string = string[0:i] + replace + string[i+len(search):]
            i += len(replace)
    return string

filename = "replace.txt"

for line in fileinput.input([filename], inplace=True):
    sys.stdout.write(replace_exclude(line, "old_string", "+new_string"))
运行replace.txt

replace.py

+new_string
-old_string

+new_string -old_string --old_string +new_string

答案 3 :(得分:-1)

这对你有用: -

import re
with open("output.txt", "a") as myfile:

    with open('input.txt') as f:
        lines = f.readlines()
        for line in lines:
            # print str(line)
            ret = re.sub(r"(\s|^|$)old_string(\s|^|$)",r" +new_string ",line) #It will replace if line contain 'old_string' by '+new_string'
            # print ret
            myfile.write(ret+'\n')

注意: - 检查output.txt