我很难在文本fi中替换一个单词

2024-09-29 23:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码可以工作,但问题是在错误的地方替换。你知道吗

有人能看看我的代码吗。你知道吗

def find():

    openfile = open(filename, "rt")

    closefile = open(filename, "wt")


    inp1 = input(search)
    inp2 = input(replace)
    for line in fileopen:
        newword = fileout.write(line.replace(inp1, inp2))

    openfile.close()
    closefile.close()
    return newword

find()

Tags: 代码closeinput地方错误lineopenfind
2条回答

正如@splash58所说,简单的方法是在单词周围加空格:

newword = line.replace(' ' + searchinput + ' ',' ' + replaceword + ' ')

更好的方法是使用regex,意思是在搜索时添加单词边界(\b

import re
newword = re.sub(r'\b{}\b'.format(searchinput),replaceword,line)

你可以用regex来做这个!正则表达式允许您搜索单词边界以及特定的子字符串。您可以为此使用\b标识符。这样你就可以确定你只学到了完整的单词,而不是当它是另一个单词的一部分时。你知道吗

import re

filterword = input('The word to replace:')
regex = "\\b" +filterword+"\\b"
replacement = input("The word to replace with:")
myString = "I tried to explain in the train."

print(f"Replacing in:\n {myString}")
print(re.sub(regex, replacement, myString))

相关问题 更多 >

    热门问题