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

    统计一个英文句子中包含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)
  • 相关阅读:
    树套树+【UVALive】6709 Mosaic 二维线段树
    汇编实验1. 计算1+2+3+…+10,将结果显示在屏幕上。4
    Tinkoff Internship Warmup Round 2018 and Codeforces Round #475 (Div. 2) D. Destruction of a Tree
    HDU 4417 Super Mario主席树
    spoj+B
    2018-2019赛季多校联合新生训练赛第五场(2018/12/14)补题题解
    迷宫问题 POJ
    浅谈二分搜索与二分查找
    Moving Tables POJ
    Humidex POJ
  • 原文地址:https://www.cnblogs.com/wenm1128/p/11616144.html
Copyright © 2011-2022 走看看