zoukankan      html  css  js  c++  java
  • Count Words in a String

    class practiceYln():
        def __init__(self):
            self.text1 = None
            self.text2 = None
    
        def cwistr(self):
            text1 = input("please input a string:")
            text2 = input("please input a string you want to search in former string: ")
            count = text1.count(text2)  # 字符串的count方法
            if count > 1:
                count = str(count)  # int转换为str,否则无法进行后面的字符串拼接
                print(text2 +" showed " + count + " times in " + text1)
            else:
                count = str(count)
                print(text2 +" showed " + count + " times in " + text1)
    
    tt = practiceYln()
    tt.cwistr()
    
    #结果是:
    please input a string:baby
    please input a string you want to search in former string: b
    b showed 2 times in baby


    # 有没有更简洁的写法呢?当然!
    class practiceYln():
    def __init__(self):
    self.text1 = None
    self.text2 = None

    def cwistr(self):
    text1 = input("please input a string:")
    text2 = input("please input a string you want to search in former string: ")
    if text1.count(text2) > 1:
    print("%s showed %d times!" % (text2, text1.count(text2)))
    # 注意引用的文体: %s对应text2(字符型),%d对应text1.count(text2)(整数型)
    elif text1.count(text2) == 1:
    print("%s showed %d time!" % (text2, text1.count(text2)))
    else:
    print("string not included")

    tt = practiceYln()
    tt.cwistr()

    #结果是:
    please input a string:baby
    please input a string you want to search in former string: z
    string not included

    #别忘记python是面向对象的编程语言,所以我们可以调用已有的包实现这一功能
    from collections import Counter
    class practiceYln():
    def __init__(self):
    self.t1 = None
    self.t2 = None
    self.t3 = None
    self.t4 = None

    def cwistr(self):
    t1 = input("please input a string:")
    t2 = input("please input a string you want to search in former string: ")
    t3 = Counter(t1)
    t4 = str(t3[t2])
    print("the string showed " + t4 + " times.")

    tt = practiceYln()
    tt.cwistr()

    # 结果是:
    please input a string:Robert
    please input a string you want to search in former string: r
    the string showed 1 times.



    May we all proceed with wisdom and grace. https://www.cnblogs.com/YlnChen/
  • 相关阅读:
    发布新闻
    下拉列表联动显示(Car表) 三级联动
    下拉列表联动显示(中国省市)三级联动
    MVC——数据库增删改查(Razor)——Html语法
    MVC——数据库增删改查(Razor)
    MVC——数据库增删改查(aspx)
    ASP.NET MVC 4 (五) 视图
    ASP.NET MVC 4 (四) 控制器扩展
    ASP.NET MVC 4 (三) 过滤器
    ASP.NET MVC 4 (二)控制器
  • 原文地址:https://www.cnblogs.com/YlnChen/p/12581535.html
Copyright © 2011-2022 走看看