python根据出现次数

时间:2017-12-03 07:55:16

标签: python string read-eval-print-loop

我对python比较陌生。我想用一个不同的单词替换一个出现两次以上的单词。单词可以包含多个单词。我希望它们被XYZ取代。例如:

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.

我使用了字典,并且能够计算一个单词的出现点。但是无法获得更换权利。我想使用regex / for循环/数据结构(如lists / dictionary)来实现此目的。是否有预先基于计数的替换功能可以实现此目的?

2 个答案:

答案 0 :(得分:2)

由于你已经有了一个字典,你想要的是循环并检查单词是否出现两次或更多并运行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")

答案 1 :(得分:1)

你可以在检查时使用str.split()和str.replace()方法的组合,例如

 b=a.split(' ',1)
 if(b.count(b[i])) > 1:
         b.replace(b[i],'XYZ')