|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目:输入一个文件名,把文件中的一个单词都替换成另一个单词。
程序:
filename =str(input("Please input filename:"))
f=open(filename,'r')
alltext=f.read()
f.close()
a=str(input("Please input the word which need to be replaced:"))
b=str(input("Please input the word to be replace with:"))
print(a)
print(b)
alltext.replace(a,b)
print(alltext)
f=open(filename,'w')
f.seek(0,0)
f.write(alltext)
f.close()
结果替换不了,我在命令行里看见replace函数明明可以替换,程序里就替换不了。
运行结果:
Please input filename:myfile.txt
Please input the word which need to be replaced:from
Please input the word to be replace with:to
from
to
be a happy name from tomorrow
dodo do do
do do do do
da di da di da
write a letter to every member in family tomorrow
to tell them my happiness
>>> alltext.replace(a,b)
'be a happy name to tomorrow\ndodo do do \ndo do do do\nda di da di da\nwrite a letter to every member in family tomorrow\nto tell them my happiness'
- f=open(filename,'w')
- f.write(alltext.replace(old,new))
- f.close()
复制代码
|
|