【问题标题】:split a list a sentence by point with python用python逐点拆分列表
【发布时间】:2019-05-15 10:52:31
【问题描述】:

我有一个句子列表:

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

但是句子没有被拆分。

有什么想法吗?

谢谢

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    使用简单的迭代和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']
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        另一种选择,但单行且以函数式编程方式:

        >>> 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 只是连接所有列表。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多