【问题标题】:splitting text further while preserving line breaks在保留换行符的同时进一步拆分文本
【发布时间】:2019-08-18 00:41:43
【问题描述】:

我正在拆分文本 para 并使用以下内容保留换行符 \n

from nltk import SpaceTokenizer
para="\n[STUFF]\n  comma,  with period. the new question? \n\nthe\n  \nline\n new char*"
sent=SpaceTokenizer().tokenize(para)

这给了我以下信息 print(sent)

['\n[STUFF]\n', '', 'comma,', '', 'with', 'period.', 'the', 'new', 'question?', '\n\nthe\n', '', '\nline\n', 'new', 'char*']

我的目标是得到以下输出

['\n[STUFF]\n', '', 'comma', ',', '', 'with', 'period', '.', 'the', 'new', 'question', '?', '\n\nthe\n', '', '\nline\n', 'new', 'char*']

也就是说,我想将'comma,'拆分'comma'',' 拆分'period.'拆分成'period',@ 987654332@ 拆分 'question?''question', '?' while 保留\n

我试过word_tokenize,它会实现拆分'comma'','等但不保留\n

如何在保留\n 的同时进一步拆分sent,如上所示?

【问题讨论】:

    标签: python string split nltk tokenize


    【解决方案1】:

    https://docs.python.org/3/library/re.html#re.split 可能就是你想要的。

    然而,从您想要的输出的外观来看,您将需要处理字符串,而不仅仅是对其应用单个函数。

    在拆分字符串之前,我会先将所有 \n 替换为 new_line_goes_here 之类的字符串,然后在拆分后将 new_line_goes_here 替换为 \n

    【讨论】:

      【解决方案2】:

      根据@randy 的建议看https://docs.python.org/3/library/re.html#re.split

      import re
      para = re.split(r'(\W+)', '\n[STUFF]\n  comma,  with period. the new question? \n\nthe\n  \nline\n new char*')
      print(para)
      

      输出(接近我要找的)

      ['', '\n[', 'STUFF', ']\n  ', 'comma', ',  ', 'with', ' ', 'period', '. ', 'the', ' ', 'new', ' ', 'question', '? \n\n', 'the', '\n  \n', 'line', '\n ', 'new', ' ', 'char', '*', '']
      

      【讨论】:

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