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/
  • 相关阅读:
    小水滴
    “星际穿越”观后感(宇宙只是界面,科技永远触摸不到世界的本原)
    惊涛怪浪(double dam-break) -- position based fluids
    [转]Data Structure Recovery using PIN and PyGraphviz
    [转]Adventures in Xen exploitation
    [转]iOS Tutorial – Dumping the Application Memory Part 2
    [转] Building xnu for OS X 10.10 Yosemite
    [转]iOS Tutorial – Dumping the Application Heap from Memory
    [转]Even when one byte matters
    [转]iOS IPC via NSFileCoordinator and NSFilePresenter
  • 原文地址:https://www.cnblogs.com/YlnChen/p/12581535.html
Copyright © 2011-2022 走看看