|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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:
- count = eachline.count(rep_word) #count感觉应该用这个
- eachline = eachline.replace(rep_word, new_word)
- content.append(eachline)
复制代码
101/5000
Zhōng yīnggāi zhǐ huì tìhuàn yīcì ba, yīn jìnrù if nèi hòu,"xiǎo"chénglì hòu, jiù wǎng xià dàimǎ yùnxíngle, pǎo wán hòu, yòu tiào xià yīxíngle, suǒyǐ wǒ xiǎng chéngshì, huì juédé dānxíng nèi rú yǒu chāoguò yīgè xiǎng tìhuàn de tóng, huì zhíxíng bù chūlái, dàn shìle hòu, bùrú wǒ xiǎngxiàng de, qǐngwèn, wǒ shì nàlǐ xiǎng cuòle.
中应该只会替换一次吧,因进入if内后,"小"成立后,就往下代码运行了,跑完后,又跳下一行了,所以我想程式,会觉得单行内如有超过一个想替换的詷,会执行不出来,但试了后,不如我想像的,请问,我是那里想错了。
- help(str.replace)
- s = '小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼'
- print(s.replace('小','大'))
复制代码
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼
|
|