首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本索引和切片

文本索引和切片
EN

Stack Overflow用户
提问于 2019-09-03 10:01:16
回答 1查看 42关注 0票数 2

我应该对每个句子进行转换,使我们只保留第三个和倒数第三个单词之间的单词(包括第三个单词和倒数第三个单词),并跳过其中的每两个单词。

jane_eyre_sentences.txt中的文本

代码语言:javascript
复制
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

我的代码如下:

代码语言:javascript
复制
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]))

我的输出:

代码语言:javascript
复制
they sore my they
the and mountains
the moonless
path poor

预期输出:

代码语言:javascript
复制
they sore my they
the and mountains
the close
path the
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-03 10:07:51

您为偶数行添加了错误的单词。您必须更改此行

代码语言:javascript
复制
print(" ".join(words[2:-4:2]), ""+ "".join(words[-3]))

代码语言:javascript
复制
print(" ".join(words[2:-4:2]), ""+ "".join(words[-4]))

您还可以去掉不必要的空字符串和第二个join,因为它是一个单词:

代码语言:javascript
复制
print(" ".join(words[2:-4:2]), words[-4])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57764196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档