繁体   English   中英

查找单词在字符串中出现的次数

[英]Find the number of times a word occurs in a string

因此,例如,如果我想知道 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) 

你这里的问题是它认为“那里”这个词中的“他”是你好的开始并且计入计数。

其他答案建议使用 string.count 函数,这就是了解标准库的经验丰富的 Python 程序员的做法。 但是,如果我查看您的方法,我会看到逻辑错误。

您的主循环有一个差一个错误。 函数range(0, n)从 0 迭代到 n-1。 在字符串 'hellotoherehello' 中,这将在您到达第二次出现的 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 顺利。

Python为此内置了一个函数: count

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

你的问题的一个很好的答案是使用嵌套的 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;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM