【问题标题】:Find the number of times a word occurs in a string查找一个单词在字符串中出现的次数
【发布时间】:2017-12-17 11:58:06
【问题描述】:

例如,如果我想知道 hello 在这个词中出现的次数:hellohellothere,我的代码会给我2,这是正确的。但是如果我有hellotherehello,我的代码不会给我2,这意味着我认为我的第二个for循环有问题。

我的代码计算字符串中的字母数,然后将其除以字符串的长度,得出字符串实际出现的次数,但我认为这不是问题所在。

这里是代码。

word = input("Enter a word: ")
find = input("Enter string to find")
count = int(0)

for x in range(0, len(word)-len(find)):
    if word[x] == find[0]:
        for i in range(0, len(find)):
            if word[x+i] == find[i]:
                count += 1
            else:  break

    count = count/len(find)

    print("Number of times it occurs is: ", count) 

【问题讨论】:

标签: python string for-loop if-statement


【解决方案1】:

其他答案推荐 string.count 函数,这就是具有标准库知识的经验丰富的 Python 程序员的做法。但是,如果我查看您的方法,我会发现逻辑错误。

您的主循环有一个错误。函数 range(0, n) 从 0 迭代到 n-1。在字符串 'hellotherehello' 中,这将在第二次出现 hello 之前结束迭代一个字符。你想要的是:

for x in range(0, len(word)-len(find) + 1):

您尝试将变量count 用于两个不同的目的:计算成功匹配的数量,以及在搜索匹配时逐个计算字符。当您已经找到一个匹配项并开始寻找第二个匹配项时,您的 count 变量将保持值 1;直到找到第一个匹配项,它是 0。更好的是一次测试一个字符是否失败而不是成功,并使用 Python 的 for:else: 构造。在循环内你会得到这个:

if word[x] == find[0]:
    for i in range(0, len(find)):
        if word[x+i] != find[i]:
            break
    else:
        count += 1

祝你学习 Python 好运。

【讨论】:

    【解决方案2】:

    你的问题是它认为'there'中的'he'是hello的开头并且计入计数。

    【讨论】:

      【解决方案3】:

      Python 有一个内置函数:count

      print("Number of times it occurs is: ", word.count(find)) 
      

      【讨论】:

        【解决方案4】:

        您的问题的一个很好的答案是使用嵌套 for 循环,但您的单词是一个单词,即 hellohellothere,JavaScript 将其视为一个单词,但如果它是这样写的 hello hello therehello there hello 有一个解决方案给你

        Let words = “hello there hello’;
        Let arrayWords = words.split(“ ”);
        Let countWords = “”;
        
        For(let i = 0; i < arrayWords.length; i++){
                  Let count = 0;
            For(let j = 0; j < arrayWords.length; j++){
                   If(arrayWords[i] === arrayWords[j]){
                        count ++;
                     countWords = arrayWords[i]
              }
           }
         Console.log(~${countWords} appeared ${count} time;
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-04-29
          • 1970-01-01
          • 2020-05-13
          • 2022-01-01
          • 2021-01-22
          • 2019-11-20
          • 2016-03-19
          相关资源
          最近更新 更多