文本索引和切片

2024-05-17 03:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该转换每个句子,使我们只保留单词之间的第三个和最后三个词(含)和跳过每一个单词的方式

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

Tags: andthepathmylinesentences单词are
1条回答
网友
1楼 · 发布于 2024-05-17 03:21:01

为偶数行添加了错误的单词。你必须改变这条线

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

相关问题 更多 >