简体   繁体   English

用python逐个分割列表

[英]split a list a sentence by point with python

I have a list of sentence : 我有一个句子列表:

['hello', 'I would like to thank you', 'I would like to thank you. By the way']

I need to split each sentence into list when I found "." 当我找到“。”时,我需要将每个句子分成列表。 .

For example, in the example above, the expected result is : 例如,在上面的示例中,预期结果是:

['hello', 'I would like to thank you', 'I would like to thank you'. 'By the way']

I try with this code in python : 我在python中尝试使用此代码:

def split_pint(result):
    for i in result:
        i = re.split(r". ", i)
    return result

But the sentence wasn't split. 但这句话没有分裂。

Any idea please? 有什么好主意吗?

Thanks 谢谢

Using a simple iteration and str.split 使用简单的迭代和str.split

Ex: 例如:

data = ['hello', 'I would like to thank you', 'I would like to thank you. By the way']

def split_pint(data):
    result = []
    for elem in data:
        result.extend(elem.split(". "))        
    return result

print(split_pint(data))

Output: 输出:

['hello', 'I would like to thank you', 'I would like to thank you', 'By the way']

That is not the way to modify a list, as you can see: 这不是修改列表的方法,如您所见:

l = [0, 0]
for x in l:
    x = 1
print(l)
# [0, 0]

Anyway, if you want to use re.split you'll need to escape . 无论如何,如果你想使用re.split你需要逃脱. character: 字符:

import re

l = ['hello', 'I would like to thank you', 'I would like to thank you. By the way']
def split_pint(result):
    res = []
    for i in result:
        res += re.split("\. ", i)
    return res


print(split_pint(l))
['hello', 'I would like to thank you', 'I would like to thank you', 'By the way']


Another option, but one-liner and in a functional programming way: 另一个选择,但是单行和功能编程方式:

>>> from functools import reduce
>>> a = ['hello', 'I would like to thank you', 'I would like to thank you. By the way']
>>> reduce(lambda i, j: i + j, map(lambda s: s.split('. '), a))
['hello', 'I would like to thank you', 'I would like to thank you', 'By the way']

First, map makes a list from each string, and second, reduce just concatenates all lists. 首先, map从每个字符串中生成一个列表,其次, reduce只是连接所有列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM