|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def all_count(name,inp_str): #这个函数用来计算文件中有多少个要替换的字符串
count=0
f=open(file_)
list_f=list(f)
for each_line in list_f:
for each in each_line:
if each==inp_str:
count+=1
return count
f.close()
def all_replace(name,inp_str,new_str):
f=open(name,'+w')
content=f.read()
content.replace(inp_str,new_str) #问题出现在这里,不知道为什么content写不进去
f.seek(0,0)
f.write(content)
f.close()
file_=input('请输入文件名')
inp_str=str(input('请输入要替换的单词或字符'))
new_str=str(input('请输入新的单词或字符'))
count=all_count(file_,inp_str) #这里调用all_count
print('文件',file_,'中共有',count,'个【',inp_str,'】\n您确定把所有的【',inp_str,'】替换为【',new_str,'】吗\n【yes/no】:')
yn=input()
if yn=='yes' or yn == 'y' or yn=='Yes'or yn=='Y':
all_replace(file_,inp_str,new_str) #这里调用all_replace
all_count函数功能正常,all_replace功能出现问题:
结果会清空文件中的所有内容,并不是‘替换字符串’
此处附上要操作的文件,要将文件中所有的‘愿’替换成‘希望’
问题详见http://bbs.fishc.com/thread-45487-1-1.html 第四题 |
|