鱼C论坛

 找回密码
 立即注册
查看: 1194|回复: 2

[已解决]第029講課後練習問題請益

[复制链接]
发表于 2018-1-14 22:47:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x

  1. def file_replace(file_name, rep_word, new_word):
  2.     f_read = open(file_name)

  3.     content = []
  4.     count = 0

  5.     for eachline in f_read:
  6.         if rep_word in eachline:
  7.             count = eachline.count(rep_word) #count感觉应该用这个
  8.             eachline = eachline.replace(rep_word, new_word)
  9.         content.append(eachline)   

  10.     decide = input('\n文件 %s 中共有%s个【%s】\n您确定要把所有的【%s】替换为【%s】吗?\n【YES/NO】:' \
  11.                    % (file_name, count, rep_word, rep_word, new_word))

  12.     if decide in ['YES', 'Yes', 'yes']:
  13.         f_write = open(file_name, 'w')
  14.         f_write.writelines(content)
  15.         f_write.close()

  16.     f_read.close()


  17. file_name = input('请输入文件名:')
  18. rep_word = input('请输入需要替换的单词或字符:')
  19. new_word = input('请输入新的单词或字符:')
  20. file_replace(file_name, rep_word, new_word)
复制代码

如果输入的文件内容中,单行就有超过一个我们想要替换的字符(如:小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼),如要把"小"替换成"大",那在
  1. for eachline in f_read:
  2.         if rep_word in eachline:
  3.             count = eachline.count(rep_word) #count感觉应该用这个
  4.             eachline = eachline.replace(rep_word, new_word)
  5.         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内后,"小"成立后,就往下代码运行了,跑完后,又跳下一行了,所以我想程式,会觉得单行内如有超过一个想替换的詷,会执行不出来,但试了后,不如我想像的,请问,我是那里想错了。
最佳答案
2018-1-15 02:00:08
  1. help(str.replace)
  2. s = '小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼'
  3. 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.

大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-1-15 02:00:08 | 显示全部楼层    本楼为最佳答案   
  1. help(str.replace)
  2. s = '小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼小甲鱼'
  3. 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.

大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼大甲鱼
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-1-15 22:53:01 | 显示全部楼层
今天再看一次我的問題,真是耍笨,但還是感謝解答。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-17 16:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表