Hi,
I´m new to Python and right now I´m trying to learn to parse a text.

Here is my code (that doesn´t work the way I want)

text = ['Mary', 'went', 'out', 'at', '7pm', 'to','buy','some','candy']
keyPerson = ['Mary', 'Clark', 'Steven']
keyTime = ['7pm', '6am', '2pm']
keyThing =['candy','eggs','fruit']

list = []
for current in text:
	for e in keyPerson:
		if e in current:
			print '--------->''%s'%e
				
	for f in keyTime:
		if f in current:
			print '--------->''%s'%f
					
	for g in keyThing:
		if g in current:
			print '--------->''%s'%g
							
							
		else:
			list.append(current)
	print list

The way I want it separated is:

#'Mary'
#'7pm'
#'candy'
#'went out at to buy some'

How can I do this?

Lists have a remove() function, so something like this should do it ...

text = ['Mary', 'went', 'out', 'at', '7pm', 'to','buy','some','candy']
keyPerson = ['Mary', 'Clark', 'Steven']
keyTime = ['7pm', '6am', '2pm']
keyThing =['candy','eggs','fruit']

# make a true copy of text list
text2 = list(text)

for current in text:
    for e in keyPerson:
        if e in current:
            text2.remove(current)
            print '--------->''%s'%e
                
    for f in keyTime:
        if f in current:
            text2.remove(current)
            print '--------->''%s'%f
                    
    for g in keyThing:
        if g in current:
            text2.remove(current)
            print '--------->''%s'%g
                            
print text2

It appears that you are trying to code one ot the two following examples. Do you want one name, time, etc., or to print all combinations of them?

##---  print one name, time, and thing ----------------------
def find_text(text_to_find, list_in):
   if text_to_find in list_in:
       ##  will return only the first item found
       return word
   return ""   ## nothing found

text = ['Mary', 'went', 'out', 'at', '7pm', 'to','buy','some','candy']
key_person = ['Mary', 'Clark', 'Steven']
key_time = ['7pm', '6am', '2pm']
key_thing =['candy','eggs','fruit']

final_list = []
append_this = [" went out at ", " to buy some "]

word_found = find_text("Mary", key_person)
final_list.append(word_found + append_this[0])

word_found = find_text("7pm", key_time)
final_list.append(word_found + append_this[1])

word_found = find_text("candy", key_thing)
final_list.append(word_found)

print "".join(final_list)
print "\n"

##-----  print all combos for one person  --------------------------
for person in key_person:
   print "%s went out at 7pm to buy candy" % (person)

Edited 7 Years Ago by woooee: n/a

I didn´t even think about the remove() function....which is a bit embarrassing :)

Thank you Vegaseat and Woooee for your help!

Well, back to the tutorials.....

This question has already been answered. Start a new discussion instead.