Me All
Me All

Reputation: 269

Printing one sentence per line after a for loop

I have a text file and I want to 1) iterate over each of its sentences, then 2) over each word of its sentences to modify some of them and then 3) print the resulting new version of the text one sentence per line

This is what I have tried so far:

import my_text

for sentence in my_text.sents():
    for word in sentence:
        if word == "the":
            print("article", end= " ")
        else:
            print("non-article", end= " ")
     if word == sentence[-1]:
        print("\n")

This code works and my text is modified and printed one sentence per line. However, there's an empty line between each sentence, and I'd like to remove that. Example:

article non-article non-article non-article

non-article non-article non-article non-article non-article non-article

article non-article non-article non-article

And this is what I want:

article non-article non-article non-article
non-article non-article non-article non-article non-article non-article
article non-article non-article non-article

How could I do that?

Upvotes: 0

Views: 599

Answers (2)

klvmungai
klvmungai

Reputation: 824

You could do this:

import my_text

for sentence in my_text.sents():
  end = " "
  for word in sentence:
    if word == sentence[-1]:
        end = "\n"
    if word == "the":
        print("article", end=end)
    else:
        print("non-article", end=end)

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

The problem is in print("\n"), the default value of end is "\n" so each time you print("\n") it prints "\n\n". Just use print():

sentences = ["the cat and dog", "the mouse and cat", "the fox and else"]
sentences = [sentence for sentence in map(str.split, sentences)]

for sentence in sentences:
    for word in sentence:
        if word == "the":
            print("article", end=" ")
        else:
            print("non-article", end=" ")

        if word == sentence[-1]:
            print()

Output

article non-article non-article non-article 
article non-article non-article non-article 
article non-article non-article non-article 

Upvotes: 1

Related Questions