简体   繁体   English

使用for循环查找字符串中单词出现的程序?

[英]Program to find the occurrence of a word in string using for loop?

I have written this code in python to count the number of occurrence of each word in python.我用python编写了这段代码来计算python中每个单词的出现次数。 I just want to do that using for loop.我只想使用for循环来做到这一点。 No other inbuilt datatype like sets or dictionary.没有其他内置数据类型,如集合或字典。 I think I have done wrong indentation.我想我做了错误的缩进。

mystring="Virat plays cricket. Virat is a batsman."
mylist=mystring.split(' ')
j=0
#the i outer loop that will iterate each element in list
for i in range(0,len(mylist)):
count=1
'''the j loop is to check whether value at j has occurred previously or not,
Like Virat at index 3 has occured previously also at index 0, so it should
not count that and it should break the loop because virat has counted previously
'''
for j in range(i-1,-1,-1):
    if mylist[i]==mylist[j]:
        break
if j==-1:
      '''if a word hasn't founded previously then it should start iterating
      next element from mylist[i]'''
      for j in range(i+1,len(mylist)):
        if mylist[i]==mylist[j]:
          count=count+1
print(mylist[i]," has occured ",count)

I think it's way easier than this.我认为这比这容易得多。

word = "tree"
phrase = "We must count how many times the word tree is included in this phrase. If I write tree again, then it's two"
counter = phrase.count(word)
print(f"The word {word} appears {counter} times")

And the output will, of course, be 2 .当然,输出将是2 I suggest you to learn writing posts on Stackoverflow if you want to avoid downvotes.如果你想避免投票,我建议你学习在 Stackoverflow 上写帖子。 I also suggest you to only use # comments and not multiline strings and browsing a little bit more before asking for help.我还建议您在寻求帮助之前只使用#注释而不是多行字符串并多浏览一下。 I admit I didn't know there was a direct way to do this task, but a fast research did the trick.我承认我不知道有直接的方法来完成这项任务,但快速研究就可以了。

Edit: if you're looking for a manual check, you can try out this:编辑:如果您正在寻找手动检查,您可以试试这个:

word_to_check = "tree"
counter = 0
phrase = "We must count how many times the word tree is included in this phrase. If I write tree again, then it's two"
phrase_array = phrase.split(" ")
for word in phrase_array:
    if word == word_to_check:
        counter = counter + 1
print(f"The word {word} appears {counter} times")

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

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