Python:用多个输入替换文本文件中的多个字符串

标签 python input replace

我正在考虑用用户的输入替换多个字符串。以下代码(这是对 stackoverflow 中的一个查询的代码的修改;请原谅,因为我再也找不到该线程了)在查找和替换指定字符串的一个实例(故意完成)时效果很好:

print('What word should we replace s1 with?')
input_1 = input()
with open('C:\\dummy1.txt')as f:
     sample1 = f.read().replace("s1", str(input_1), 1)
with open('C:\\dummy2.txt',"w") as f1:
     f1.write(sample1)

现在,当我尝试复制粘贴相同内容并修改它以适应其他字符串时,只有最后一个指定的字符串被替换......这是一个示例代码:

print('What word should we replace s1 with?')
input_1 = input()
with open('C:\\dummy1.txt')as f:
     sample1 = f.read().replace("s1", str(input_1), 1)
with open('C:\\dummy2.txt',"w") as f1:
     f1.write(sample1)

print('What word should we replace s2 with?')
input_2 = input()
with open('C:\\dummy1.txt')as f:
     sample2 = f.read().replace("s2", str(input_2), 1)
with open('C:\\dummy2.txt',"w") as f1:
     f1.write(sample2)

我需要做什么才能使多个字符串无缝工作?请考虑向具有不到一年编码经验和 9 小时 Python 视频学习经验的人解释它:) 谢谢!

最佳答案

这对我有用。

#using os to get path since py and txt file are in same folder
#just change your actual path if you need
import os
curdir=os.getcwd()
filepath=os.path.join(curdir,'the_file.txt')


print('What word should we replace s1 with?')
input_1 = input()
print('What word should we replace s2 with?')
input_2 = input()

sample1=''
sample2=''
with open(filepath, 'r')as f:
     sample1 = f.read().replace("s1", str(input_1), 1)
     sample2 = sample1.replace("s2", str(input_2), 1)
with open(filepath, 'w')as f:    
     f.write(sample2)

编辑:

此外,我刚刚意识到,您在获取输入和替换文本时两次都从 dummy1.txt 读取并写入 dummy2.txt。这就是仅更改 s2 的原因。更改 s2 时,您应该读取 dummy2.txt,因为该文件包含 s1 更改。在上面的示例中,我只是覆盖了我读取的文件,但如果您愿意,可以轻松更改。

    #using os to get path since py and txt file are in same folder
#just change your actual path if you need
import os
curdir=os.getcwd()
filepath=os.path.join(curdir,'the_file.txt')
filepath_2=os.path.join(curdir,'the_other_file.txt')


print('What word should we replace s1 with?')
input_1 = input()
print('What word should we replace s2 with?')
input_2 = input()

sample1=''
sample2=''
with open(filepath, 'r')as f:
     sample1 = f.read().replace("s1", str(input_1), 1)
     sample2 = sample1.replace("s2", str(input_2), 1)
with open(filepath_2, 'w')as f:    
     f.write(sample2)

关于Python:用多个输入替换文本文件中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47057347/

相关文章:

python - Robot Framework 的 Mongo Db 扩展库返回错误记录

javascript - 如何将输入存储到 HTML 和 Javascript 中的变量中?

r - 使用 setNames 替换 R 数据框列中的多个值时出现奇怪的行为

bash - 我可以使用 sed 来操作 bash 中的变量吗?

java - Wicket - 确认面板更换/删除以保存未保存的数据

Python:使用用于单元测试的文件创建模拟或假目录

python - 用于 Python 的 Parfor

python - 如何在不下载文章的情况下使用Newspaper3k库?

html - 在页面中将标签和输入居中

C++:在空格字符后获取字符而不是返回回车