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

时间:2017-11-01 14:37:11

标签: python input replace

我正在考虑用来自用户的输入替换多个字符串。下面的代码(这是对stackoverflow中的一个查询的代码的修改; pardon coz我再也找不到该线程)在查找和替换指定字符串的一个实例(有意完成)时效果很好: / p>

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)

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

4 个答案:

答案 0 :(得分:1)

这对我有用。

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

答案 1 :(得分:0)

我认为你想要的是,在第二个例子中,以追加模式打开文件C:\\dummy2.txt文件而不是写入模式(覆盖任何先前的输出),例如,使用open('C:\\dummy2.txt',"a")而不是open('C:\\dummy2.txt',"w")

答案 2 :(得分:0)

对于更短的代码,您可以同时获取两个字符串并链接替换方法:

replacement_strings = input('Please enter S1 and S2, separated by hyphen :').split('-')
with open('C:\\dummy1.txt')as f:
    sample1 = f.read().replace("s1", replacement_strings[0]).replace("s2", replacement_strings[1]) if len(replacement_strings) > 1 else f.read().replace("s1", replacement_strings[0]) if replacement_strings
with open('C:\\dummy2.txt',"w") as f1:
    f1.write(sample1)

注意:对于python 2.x,您需要使用raw_input()而不是input()

答案 3 :(得分:0)

我找到了一种在Python中轻松查找替换字符串的方法。

在此示例中,将find [0]替换为replace [0]等。

语句“ x = line.replace(find [0],replace [0])。replace(find [1],replace [1])...”被动态创建为一个字符串,此字符串后来被执行。

我使用此脚本将单词docx转换为HTML文件,然后在该HTML文件中更改了多个字符串。

import mammoth
import os
import fileinput    

#set source, output
source = 'test.docx'
output = 'output.html'    

#set find and replace, e.g. find[0] will be replaced by replace[0]
find = ['a', '1']
replace = ['b', '2']    

#convert to html in temp file
temp = '.temp.html'
f = open(source, 'rb')
b = open(temp, 'wb')
document = mammoth.convert_to_html(f)
b.write(document.value.encode('utf8'))
f.close()
b.close()    

#create a find-and-replace statement
i = 0
c = len(find)
string = "x = line"
while i < c: 
    x = ".replace(find[" + str(i) + "], replace[" + str(i) + "])"
    string = string + x
    i = i + 1    

#write output file
f = open(output, 'wb')
with fileinput.FileInput(temp, inplace=False, openhook=fileinput.hook_encoded('utf-8', 'surrogateescape')) as file:
    for line in file:
        #execute the find-and-replace statement
        exec(string)
        f.write(x.encode('utf-8'))
f.close()    

#remove temp file
os.remove(temp)