Skip to main content
 首页 » 编程设计

python之文本索引和切片

2024年11月01日9JeffreyZhao

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

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