Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating an index of words
    text
    copied!<p>I'm currently trying to create an index of words, reading each line from a text file and checking to see if the word is in that line. If so, it prints out the number line and continues the check. I've gotten it to work how I wanted to when printing each word and line number, but I'm not sure what storage system I could use to contain each number.</p> <p>Code example:</p> <pre><code>def index(filename, wordList): 'string, list(string) ==&gt; string &amp; int, returns an index of words with the line number\ each word occurs in' indexDict = {} res = [] infile = open(filename, 'r') count = 0 line = infile.readline() while line != '': count += 1 for word in wordList: if word in line: #indexDict[word] = [count] print(word, count) line = infile.readline() #return indexDict </code></pre> <p>This prints the word and whatever the count is at the time (line number), but what I'm trying to do is store the numbers so that later on I can make it print out</p> <pre><code>word linenumber word2 linenumber, linenumber </code></pre> <p>And so on. I felt a dictionary would work for this if I put each line number inside a list so each key can contain more than one value, but the closest I got was this:</p> <pre><code>{'mortal': [30], 'dying': [9], 'ghastly': [82], 'ghost': [9], 'raven': [120], 'evil': [106], 'demon': [122]} </code></pre> <p>When I wanted it to show up as:</p> <pre><code>{'mortal': [30], 'dying': [9], 'ghastly': [82], 'ghost': [9], 'raven': [44, 53, 55, 64, 78, 97, 104, 111, 118, 120], 'evil': [99, 106], 'demon': [122]} </code></pre> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload