count (how to find all letters, and count them)

Question:

How to make = 2(there are two "the")

import re
text = "there are a lot of the cats"
o = re.findall("the", text)
print(o)


def text(word):
    count = 0
    for word in text:
        if "ou" in text:
            count += 1
    return count

print(count)

print(i)

this code should return 2 (because there are 2 "the")

Asked By: Elina Makipova

||

Answers:

If you want to get all words and count them here is the code:

text = input("Your text: ")
words_in_text = {}
for word in text.lower().split(" "):
    if word in words_in_text.keys():
        words_in_text[word] += 1
    else:
        words_in_text[word] = 1

To get a number of words simply use:

word_to_get = input("Which word to check: ")
print(words_in_text[word_to_get])

Here is a nice printed format for all words:

print("nWord | Count")
for word, count in words_in_text.items():
    print(f"{word}: {count}")

Output:

Your text: My name is Echo Echo

Word | Count
my: 1
name: 1
is: 1
echo: 2
Answered By: BokiX

@chris is is right. You are successfully doing it on line 3 and 4, but line 4 returns it in an array ['the', 'the']. In python you can get the ‘length’ of an array/list (how many things are in it) with len(yourArrayHere).

So if you want to just see the count you can do:

print(len(o))

if you want to save it to a variable,
on line 5 just do this:

count = len(o)

everything after that is not needed

Answered By: Aaron
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.