Python 在for循环后每行打印一句话

Python 在for循环后每行打印一句话,python,Python,我有一个文本文件,我想1)遍历它的每个句子,然后2)遍历它的每个句子中的每个单词来修改其中的一些,然后3)打印文本的新版本,每行一句 这就是我迄今为止所尝试的: import my_text for sentence in my_text.sents(): for word in sentence: if word == "the": print("article", end= " ") else: pri

我有一个文本文件,我想1)遍历它的每个句子,然后2)遍历它的每个句子中的每个单词来修改其中的一些,然后3)打印文本的新版本,每行一句

这就是我迄今为止所尝试的:

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")
这段代码有效,我的文本每行修改和打印一句话。然而,每个句子之间都有一条空行,我想删除它。例如:

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
这就是我想要的:

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

我该怎么做?

问题在于
打印(“\n”)
,end的默认值是
“\n”
,因此每次
打印(“\n”)
,它都会打印
“\n\n”
。只需使用
print()

输出

article non-article non-article non-article 
article non-article non-article non-article 
article non-article non-article non-article 
您可以这样做:

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)
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)