• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

python根据发生次数替换单词

python 来源:kayvwar 2次浏览

我对python比较陌生。我想用一个不同的词来替换出现两次以上的单词。单词可以由多个单词组成。我希望他们被XYZ取代。例如:python根据发生次数替换单词

ABC is a tall person. ABC likes sports. Sports are good for health. ABC is a gold medalist in many sports. 

ABC和运动应该替换为XYZ。像,上面的句子应该是:

XYZ is a tall person. XYZ likes XYZ. XYZ are good for health. XYZ is a gold medalist in many XYZ. 

我用字典,并能够得到一个单词的计数点。但是无法获得替代权。我想要使​​用正则表达式/ for循环/数据结构(如列表/字典)来完成此操作。是否有基于计数的替代功能可以提前完成?


===========解决方案如下:

已经有一本字典既然你,你要的是循环并检查字出现两次以上,运行与string.replace(),使用示例:

s = ABC is a tall person. ABC likes sports. Sports are good for health. ABC is a gold medalist in many sports. 

s.replace("ABC", "XYZ") 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)