def paraula(file,wordtofind):
f = open(file,"r")
text = f.read()
f.close()
count = 0
for i in text:
s = i.index(wordtofind)
count = count + s
return count
paraula (file,wordtofind)
Asked
Active
Viewed 1,307 times
2

mbinette
- 5,094
- 3
- 24
- 32
-
What have you tried and what exception did you get? There are at least two exceptions you'll hit with the code as-is that have nothing to do with counting words in a string. – CivFan Oct 02 '15 at 23:06
-
`for i in text` will return each character one by one, so all other things equal you'll only find single character words that way. Next, assuming that's resolved, `s = i.index(...)` will return the position in the string the word was found, so incrementing by `s` will skew your count considerably. Also, if the word isn't found, [you'll get a `ValueError` exception](https://docs.python.org/2/library/string.html). This is actually to your advantage, because you don't really care about the index, you just want to know if it was found or not. – CivFan Oct 02 '15 at 23:17
-
Finally, [do you care about overlapping matches](http://stackoverflow.com/questions/5616822/python-regex-find-all-overlapping-matches)? – CivFan Oct 02 '15 at 23:23
2 Answers
3
def word_count(filename, word):
with open(filename, 'r') as f:
return f.read().count(word)
0
def paraula(file,wordtofind):
f = open(file,"r")
text = f.read()
f.close()
count = 0
index = text.find(wordtofind) # Returns the index of the first instance of the word
while index != -1:
count += 1
text = text[index+len(wordtofind):] # Cut text starting from after that word
index = text.find(wordtofind) # Search again
return count
paraula (file,wordtofind)

mbinette
- 5,094
- 3
- 24
- 32