我应该对每个句子进行转换,使我们只保留第三个和倒数第三个单词之间的单词(包括第三个单词和倒数第三个单词),并跳过其中的每两个单词。
jane_eyre_sentences.txt中的文本
My feet they are sore and my limbs they are weary
Long is the way and the mountains are wild
Soon will the twilight close moonless and dreary
Over the path of the poor orphan child我的代码如下:
for line in open("jane_eyre_sentences.txt"):
line_strip = line.rstrip()
words = line_strip.split()
if len(words)%2 == 0:
print(" ".join(words[2:-4:2]), ""+ "".join(words[-3]))
else:
print(" ".join(words[2:-3:2]),""+ "".join(words[-3]))我的输出:
they sore my they
the and mountains
the moonless
path poor预期输出:
they sore my they
the and mountains
the close
path the发布于 2019-09-03 10:07:51
您为偶数行添加了错误的单词。您必须更改此行
print(" ".join(words[2:-4:2]), ""+ "".join(words[-3]))至
print(" ".join(words[2:-4:2]), ""+ "".join(words[-4]))您还可以去掉不必要的空字符串和第二个join,因为它是一个单词:
print(" ".join(words[2:-4:2]), words[-4])https://stackoverflow.com/questions/57764196
复制相似问题