0

I'm trying to find whenever one of some specific words is used in a TXT file and then count what number word in the file the word is. My code returns the number for some but not all of the words, and I have no idea why.

My code right now goes through the file word by word with a counter and returns the number if the word matches one of the words I want.

def wordnumber(file, filewrite, word1, word2, word3):
    import os
    wordlist = [word1, word2, word3]
    infile = open(file, 'r')
    g = open(filewrite, 'w')
    g.write("start")
    g.write(os.linesep)
    lines = infile.read().splitlines()
    infile.close()
    wordsString = ' '.join(lines)
    words = wordsString.split()
    n = 1
    for w in words:
        if w in wordlist:
            g.write(str(n))
            g.write(os.linesep)
        n = n+1

This works sometimes, but for some text files it only returns some of the numbers and leaves others blank.

Jmonsky
  • 1,519
  • 1
  • 9
  • 16
max
  • 11
  • 4
  • @max If you have `g.close()` as your last line, _after_ the loop, does that fix the problem? – SpoonMeiser Jul 16 '19 at 14:33
  • no, it's still not counting all the words – max Jul 16 '19 at 14:40
  • It is better to use `with open(filename, 'r') as infile: infile_lines = infile.readlines()` Check for `with statement` on [this page](https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) – D. LaRocque Jul 16 '19 at 15:14

1 Answers1

0

If you want find the first occurence of the word in your words, just use

wordIndex = words.index(w) if w in words else None

and for all occurences use

wordIndexes = [i for i,x in enumerate(words) if x==word] 

(taken from Python: Find in list) But beware: if your text is "cat, dog, mouse", your code wouldn't find index of "cat" or "dog". Because "cat, dog, mouse".split() returns ['cat,', 'dog,', 'mouse'], and 'cat,' is not 'cat'.

Hyyudu
  • 134
  • 1
  • 7