python根据发生次数替换单词

我对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")

回答:

可以使用STR的组合.split()和str.replace()方法,例如

b=a.split(' ',1) 

if(b.count(b[i])) > 1:

b.replace(b[i],'XYZ')

以上是 python根据发生次数替换单词 的全部内容, 来源链接: utcz.com/qa/259969.html

回到顶部