【问题标题】:Locating starting and ending points inside of strings python在字符串python中定位起点和终点
【发布时间】: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


【解决方案1】:

我不确定问题是什么,但是如果您想记录在列表中的哪个位置找到了包含起点或终点的元素,您可以这样打印:

sentence1 = ['some','   ','empty','sentences that ,', 'Im looking for','to find','end ',"",'end point',"maybe"]
for i, word in enumerate(sentence1 ):
    if start in word:
        print(i)
    if end in word:
        print(i)

也许是收集起始号码:

start_indexes = [ i for i, word in enumerate(sentence1 ) if start in word ]
end_indexes = [ i for i, word in enumerate(sentence1 ) if end in word ]

然后,如果您可以确保没有重复的 starts 彼此相邻且它们之间没有 end,您可以合并列表,并且每对将包含一个切片。 也可以这样制作:

indexes = [ i for i, word in enumerate(sentence1 ) if start in word or end in word ]


for i in range(len(indexes/2)):
    print( sentence1 [ indexes[i*2] : indexes[i*2 + 1] + 1] )

希望我能理解你的问题

【讨论】:

  • 我在帖子中犯的错误是“sentence1”和“sentence2”是一个字符串而不是一个列表。所以 sentence1 sentence2 (字符串)一起在一个列表中,但它不是一个嵌套列表。所以可能我必须从它们中创建一个嵌套列表才能切片..(我已经更新了帖子)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
相关资源
最近更新 更多