簡體   English   中英

Python:將字符串替換為文件中的變量

[英]Python: Replace a string as variable in a file

如果我有這樣的文件內容:

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)      

語法有點偏; 你可能想要做更像這樣的事情:

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

您可以忽略開頭帶有連字符(“ - ”)的行,並替換其余行。

下面的腳本與您的腳本略有不同。 我已提出意見以幫助您理解。 這應該很容易理解。

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()

我的解決方案的一個好處是它不依賴於行的開頭的“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

這對你有用: -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM