python - 在保留换行符的同时进一步拆分文本
问题描述
我正在使用以下内容拆分文本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'
'.'
'question?'
'question'
'?'
while
\n
我已经尝试过word_tokenize
,它将实现拆分'comma'
等','
但不保留\n
在保留的同时,我可以做些什么来进一步拆分sent
如上所示\n
?
解决方案
https://docs.python.org/3/library/re.html#re.split可能是您想要的。
然而,从您想要的输出的外观来看,您需要对字符串进行更多处理,而不仅仅是对其应用单个函数。
我会先\n
用一个字符串替换所有的,就像new_line_goes_here
在拆分字符串之前一样,然后在它全部拆分后new_line_goes_here
替换。\n
推荐阅读
- vue.js - Vue 向其他组件发送数据是落后了一步
- php - PHP:警告:json_decode() 期望参数 1 是字符串,对象在
- c# - 正则表达式帮助:尝试获取特定字符串后面的数字
- symfony - Symfony:实现来自外部项目的身份验证
- html - 我无法删除字母之间的间距。即使字母间距为 0px,它仍然有太多空间
- python - 通过 python psycopg2 中的列名检索值
- java - Java - 简单的旋转动画
- domain-driven-design - 聚合之间的关联,如何决定是持有对对象的引用还是仅持有其标识
- c# - 我怎样才能忽略14个标点符号
- css - 渐变字体真棒在反应