I feel disgraced by asking about the solution of my "homework" here. But I have already spent 4 hours on it, cannot continue like this.
Assignment: count occurrences of a specific string inside a Lorem Ipsum text (already given); a helper function tokenize that splits a given text and returns a list of tokens has been provided.
def tokenize(text):
return text.split()
for token in tokenize(text):
print(token)
Task: Write a function search_text()
which takes two parameters in this order: filename
and query
.
The function should return the number of occurrences of query
inside the file filename
.
query = 'ipsum'
search_text('lorem-ipsum.txt', query) # returns 24
My code:
def tokenize(text):
return text.split()
def search_text(filename, query):
with open("lorem-ipsum.txt", "r") as filename:
wordlist = filename.split()
count = 0
for query in wordlist:
count = count + 1
return count
query = "lorem"
search_text('lorem-ipsum.txt', query)
It doesn't work and looks a little bit mess. To be honst, I don't unterstand how the function tokenize()
works here.
Could someone give me a hint?