|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def file_replace(file_name, rep_word, new_word):
f_read = open(file_name)
content = []
count = 0
for eachline in f_read:
if rep_word in eachline:
count = eachline.count(rep_word) #count感觉应该用这个
eachline = eachline.replace(rep_word, new_word)
content.append(eachline)
decide = input('\n文件 %s 中共有%s个【%s】\n您确定要把所有的【%s】替换为【%s】吗?\n【YES/NO】:' \
% (file_name, count, rep_word, rep_word, new_word))
if decide in ['YES', 'Yes', 'yes']:
f_write = open(file_name, 'w')
f_write.writelines(content)
f_write.close()
f_read.close()
file_name = input('请输入文件名:')
rep_word = input('请输入需要替换的单词或字符:')
new_word = input('请输入新的单词或字符:')
file_replace(file_name, rep_word, new_word)
就是
for eachline in f_read:
if rep_word in eachline: 为什么用rep_word == eachline 就不行..... 为什么用in?..
count = eachline.count(rep_word) #count感觉应该用这个
eachline = eachline.replace(rep_word, new_word)
content.append(eachline)
rep_word是你输入的单词或字符,而eachline是你从打开文件获取的每一句而不是词或字符;
要两者相等须得是从文件中获取的一句中就只有一个词或字符;
例如:你打开了一个txt文件,内容为:
we must fight for ourselves;
else we will died;
然后你获取的第一个eachline应该是'we must fight for ourselves;'这时候除非你输入的rep_word是这个句子,否则eachline不会等于rep_word
如果你还有点不理解,你试试在你代码里的'if rep_word in eachline'下加一句:
print ('The rep_word is:%s\nThe eachline is:%s'%(rep_word,eachline))
|
|