Exactly like you said, using a dictionary:
d = {}
lineCount = 1
q = raw_input("enter something: ")
while q != "no":
lineCount += 1
q = raw_input("enter something: ")
d[lineCount] = q
Then you could just query your dictionary if you want to know what the user input at a desired line as d[desired_line]
.
Assuming you have a simple dictionary, such as:
d = {2: 'b', 3: 'c', 4: 'd', 5: 'no', 6: 'c'}
Then if you'd like to print out the lines where a desired word appear you could define a function like so:
def print_lines(my_dict, word):
lines = [line for line, ww in my_dict.iteritems() if ww == word]
return lines
You could call this function with your dictionary (d
) and the word your looking for, let's say 'c':
print_lines(d, 'c')
Finally, could iterate over the set of words (unique_words
using set
) you have and print the lines they appear on by calling the previous function:
def print_words(my_dict):
unique_words = set([word for word in my_dict.itervalues() if word != 'no'])
for word in sorted(unique_words):
print("'{0}' occurs in lines {1}".format(word, print_lines(my_dict, word)))
UPDATE (for sentences instead of single words):
In case you want to work with sentences, rather than single words per line, you'll need to modify your code as follows:
First, you could define a function to handle the user input and build the dictionary:
def build_dict():
d = {}
lineCount = 1
q = raw_input("enter something: ")
while q != "no":
d[lineCount] = q
lineCount += 1
q = raw_input("enter something: ")
return d
Let's say you build a dictionary like such:
d = {1: 'a x', 2: 'a y', 3: 'b x'}
Then you can define a helper function that tells you at which line a particular word occurs:
def occurs_at(my_dict, word):
lines = [line for line, words in my_dict.iteritems() if word in words]
return lines
Finally, you can query this function to see where all your words occur at (and you can decide which words to ignore, e.g. 'a').
def print_words(my_dict, ignored=['a']):
sentences = [sentences.split(' ') for sentences in my_dict.itervalues()]
unique_words = set([word for sentence in sentences for word in sentence])
for word in sorted(unique_words):
if word not in ignored:
print("'{0}' occurs in lines {1}".format(word, occurs_at(my_dict, word)))