用python

时间:2019-05-15 10:52:31

标签: python regex python-3.x

我有一个句子清单:

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

当我找到“”时,我需要将每个句子分成列表。

例如,在上面的示例中,预期结果是:

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

我尝试在python中使用以下代码:

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

但是句子并没有分开。

有什么想法吗?

谢谢

3 个答案:

答案 0 :(得分:4)

使用简单的迭代和str.split

例如:

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))

输出:

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

答案 1 :(得分:1)

这不是修改列表的方法,如您所见:

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

无论如何,如果要使用re.split,则需要转义.字符:

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']


答案 2 :(得分:1)

另一种选择,但采用一种功能编程的方式:

>>> 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']

首先,map从每个字符串组成一个列表,其次,reduce仅连接所有列表。