在Python中拆分后获取包含的字符串数组

时间:2017-11-16 21:17:57

标签: python python-3.x

如果我有一些文字:

 text= "  First sentence. Second sentence. Third sentence."

然后我分开'。':

 new_split = text.split('.')

我会收到:['First sentence', Second sentence','Third sentence']

如果我打电话,我怎么能打印整个第二句呢?

像:

if 'second' in new_split : print (new_split[GET SECOND SENTENCE])

如果我知道在我的分词中存在一个包含我的关键字的句子,我想知道如何获得整个'第二句话'。

4 个答案:

答案 0 :(得分:2)

text= "  First sentence. Second sentence. Third sentence."

[print(i) for i in text.split('.') if "second" in i.lower()]

prints

 Second sentence

以上是我可以考虑用lines执行此操作的最短路径,但您只需使用for-loop而非list-comp轻松完成此操作:

for sentence in text.split('.'):
    if "second" in sentence.lower():
        print(sentence)

答案 1 :(得分:2)

要查找包含给定子字符串的句子列表中第一个句子的索引:

i = next(i for i, sentence in enumerate(sentences) if word in sentence)

简单的Python也是如此:

for i, sentence in enumerate(sentences):
    if word in sentence:
        break
else:
    # the word is not in any of the sentences

答案 2 :(得分:1)

你可以试试这个:

text= "  First sentence. Second sentence. Third sentence."
new_text = [i for i in text.split('.') if "second" in i.lower()][0]

输出:

' Second sentence'

答案 3 :(得分:0)

试试这个:

if new_split[1] != '': 
    print(new_split[1])