gpt4 book ai didi

python - 文本索引和切片

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:40 25 4
gpt4 key购买 nike

我应该转换每个句子,以便我们只保留第三个和倒数第三个单词(含)之间的单词,并在途中跳过每个第二个单词。

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

最佳答案

您为偶数行附加了错误的单词。你必须改变这一行

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

关于python - 文本索引和切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com