Droid-Bird
Droid-Bird

Reputation: 1505

How to iterate a list of words to find word with some pattern?

I want to merge tagged city names of two words, and print. How can I move the iterator forward and do that with loop(s)?

sentence = "There are many cities. Random text, city name <c.first> New </c.first> <c.last> York </c.last> and text continues."
sentence = sentence.split()

#print(sentence)

for word in sentence:
    if(word == '<c.first>' ):
        print(word)
      # Here I want to be able to find New York, as single element and print. Output 'New York'

Upvotes: 0

Views: 45

Answers (2)

Droid-Bird
Droid-Bird

Reputation: 1505

Thanks to @Ollie for the idea, that I could find the solution to my problem. I want to count the entire city name as one entity somehow. Not sure if this is an efficient way though. So, I would still welcome suggestion(s).

sentence = "There are many cities. Random text, city name <c.first> New City of </c.first> <c.last> York </c.last> and text continues.  <c.first> A LONG </c.first> <c.last> STRANGE CITY NAME </c.last>"
sentence = sentence.split()

found_tag = False

#tags = ['<c.first>', '</c.first>', '<c.last>','</c.last>']

opening_tags = ['<c.first>',  '<c.last>']
closing_tags = ['</c.first>', '</c.last>']

for word in sentence:
    if(word in opening_tags):
        found_tag = True
    elif found_tag and word not in closing_tags:
        print(word, end =' ')
    elif word in closing_tags:
        found_tag = False

Upvotes: 1

Ollie
Ollie

Reputation: 1712

If you want to just print out all the words after each tag, then you can do the following, where tags is a list of tags.

sentence = "There are many cities. Random text, city name <c.first> New </c.first> <c.last> York </c.last> and text continues."
sentence = sentence.split()

found_tag = False

tags = ['<c.first>', '<c.last>']

for word in sentence:
    if(word in tags):
        found_tag = True
    elif found_tag:
        print(word)
        found_tag = False

This will print:

New
York

Upvotes: 1

Related Questions