【问题标题】:How many times a different word appear in a string - python字符串中出现不同单词的次数 - python
【发布时间】:2021-02-17 02:57:23
【问题描述】:

例如我有GolDeNSanDyWateRyBeaChSand,我需要找出sand这个词出现了多少次。

text = input()
text = text.lower()
count = 0

if "sand" in text:
    count += 1

print(count)

但问题是这个字符串中有 2 个sand,当它找到第一个时它就停止了。我是编程初学者。

【问题讨论】:

  • 您可以使用内置函数(如 text.count())或两个指针方法(l - 第一个符号,r - 最后一个,向前滑动窗口并检查子字符串 text[l:r +1] 而 r

标签: python


【解决方案1】:

您可以简单地使用 str.count() 方法来计算一个字符串在另一个字符串中出现的次数。

text = input()
text = text.lower()
count = text.count("sand")

【讨论】:

    【解决方案2】:

    要在另一个字符串 s 中查找字符串 pattern 的每个匹配项,即使是嵌套匹配项,请执行以下操作:

    s = "sandsandssands"  # your string here
    pattern = "sands"     # your pattern here
    
    pos = -1
    end_of_string = False
    
    while not end_of_string:
        pos = s.find(pattern, pos+1)
        print(pos)
        end_of_string = (pos == -1)
    

    输出

    0
    4
    9
    -1
    

    【讨论】:

      【解决方案3】:

      扩展 OP 提供的解决方案。
      这个想法是使用find 并移到字符串的末尾。
      很明显count可以在这里使用,下面的解决方案是为了教育目的。

      text = 'GolDeNSanDyWateRyBeaChSand'
      word = 'sand'
      ltext = text.lower()
      offset = 0
      counter = 0
      while True:
          idx = ltext.find(word, offset)
          if idx == -1:
              break
          else:
              counter += 1
              offset = idx + len(word)
      print(f'The word {word} was found {counter} times')
      

      输出

      The word sand was found 2 times
      

      【讨论】:

        猜你喜欢
        • 2022-07-05
        • 1970-01-01
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 2015-09-14
        相关资源
        最近更新 更多