【发布时间】:2021-06-23 11:23:42
【问题描述】:
在一个叫 main 的变量中,它是一个列表,每一行中有多个字符串,每个索引下的句子。在这些字符串中会出现常见的单词。
这个想法是在我的案例中定位那些经常出现的单词('sentences that' - 句子的开头)和'end point'作为句子的结尾。最终目标是获取从 ('sentences that') 行一直到遇到 'end point' 单词的信息,并将其全部放在一个列表中。
代码:
sentence1 = "some \n empty sentences that \n Im looking for to find \n end \n end point \n maybe"
sentence2 = "everytime \n,\n sentences that \n come \n start to \n end point "
main = [sentence1,sentence2]
输出语句1:
some
empty sentences that
Im looking for to find
end
end point
maybe
#OUTPUT sentence2:
everytime
,
sentences that
come
start to
end point
尝试:
#code
sentence1 = "some \n empty sentences that \n Im looking for to find \n end \n end point \n maybe"
sentence2 = "everytime \n,\n sentences that \n come \n start to \n end point "
main = [sentence1,sentence2]
start = 'sentences that'
end = 'end point'
for i,e in enumerate(main):
for j in e:
if start in e:
print(j.find(start))
if end in e:
print(j.find(end))
输出:
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
手动展示 - 所需的输出
eventual manual code output:
print( main[0][3:9])
print( main[1][3:7])
# DESIRED OUTPUT:
# main[0]
empty sentences that
Im looking for to find
end
end point
# main[1]:
sentences that
come
start to
end point
对于句子 1:一些,也许 - 单词被排除在外 对于 sentence2:everytime 和逗号 (,) - 被排除在外
【问题讨论】:
-
您对下面的提案有任何疑问或问题吗?
-
@rawrex 给出的建议与我的几乎相同,只是您使用了 index(),这没关系,因为这就是想法。但是,如果还没有,我已经更正了帖子以使其更清楚。这个想法是在检测到某个单词时用起点和终点进行切片。
标签: python list indexing nested-lists