首页 > 其他 > 详细

统计一个英文句子中包含2个a的单词有几个,并将两个a替换为星号,不能用count函数

时间:2019-10-01 22:22:27      阅读:118      评论:0      收藏:0      [点我收藏+]

统计一个英文句子中包含2个a的单词有几个,并将两个a替换为星号,不能用count函数

def count(s,x):
    if (not isinstance(s,str)) or (not isinstance(x,str)):
        return None
    num =0
    i = 0
    while i<=len(s)-1:
        if s[i:i+len(x)]==x:
            num+=1
            i+=len(x)
        else:
            i+=1
    return num
 
print(count("abcdbcd","bb"))
 
s = "I am a abandon,aaaa  boy aabbaa  aacc!"
s=list(s)
new_s=[]
for i in s:#过滤标点,只保留空格和大小写字母
    if i ==" " or ((i >="a" and i<="z") or \
(i >="A" and i<="Z")):
        new_s.append(i)
    else:
        new_s.append(" ")
s="".join(new_s)
result_num=0
word_list = s.split()  #取出来单词列表
new_sentence=""   #存储替换后的结果
for word in word_list:  #遍历单词列表
    if count(word,"a")==2: #如果有2个a,则进行计数并替换星号
        result_num+=1
        new_word = ""
        for i in word: #查找每个字母是否是a
            if i!="a": #不是a则保留
                new_word+=i
            else:      #是a则替换为星号
                new_word+="*"
        new_sentence+=new_word+" "  #存储在新的句子变量中
    else:
        new_sentence+=word+" " #存储在新的句子变量中
 
new_sentence=new_sentence[:-1] #去掉最后的空格
print("包含a的单词一共:%s 个" %result_num)
print(new_sentence)

统计一个英文句子中包含2个a的单词有几个,并将两个a替换为星号,不能用count函数

原文:https://www.cnblogs.com/wenm1128/p/11616144.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!