当我正在运行一个程序时,我想用我的替换文本替换搜索到的文本。然而,在第一个实例中,它做了很好的工作,但在运行下一个实例时,它没有生成所需的输出。
search_text = "something"
replacement_text = "\""+search_text+"\""
第一次运行:
Input : something
Output : "something"
第二次运行:
Input: something
Output: ""something""
第二次运行所需的输出:
not found
所以,我想打印一个无法找到精确匹配的错误,或者我想找出文本文件中搜索单词的紧邻左侧字符。
代码如下:
texterror = ["a","b","c","d"]
def dothereplace(search_text, replace_text):
with open(filepath, "r", encoding="utf-8") as file:
data = file.read()
data = data.replace(search_text, replace_text)
with open(filepath, 'w', encoding='utf-8') as file:
file.write(data)
search_text = ""
replace_text = ""
for i in range(0,len(texterror)):
search_text = texterror[i]
replace_text = "\""+search_text+"\""
dothereplace(search_text,replace_text)
print(texterror[i],"replacement done")
这真的很奇怪,为什么第二次运行会是
not found
?显然 something
在 "something"
中。
如果出于某种原因你只想用“word”替换一个单词一次,那么你必须编写自己的替换方法来专门忽略用引号引起来的search_text,而不是使用data.replace()
通过函数调用在开头搜索 Replaced_text 来解决它
def search_in_file(replace_text):
with open(filepath,"r",encoding="utf-8") as file:
data_show = file.readlines()
for row in data_show:
word = replace_text
return row.find(word)
# if search_in_file returns -1 that means replace text not available and dothereplace and if it's 0 then no replacement replacement already dond