基于空格和尾随标点的符号化?

2024-09-30 20:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用正则表达式将字符串拆分为基于空格或尾随标点的列表。在

例如

s = 'hel-lo  this has whi(.)te, space. very \n good'

我想要的是

^{pr2}$

s.split()让我大部分时间都在那里,只是它不处理后面的空白。在


Tags: 字符串lo列表spacethisverysplithas
3条回答

使用spacy的粗糙解。它已经可以很好地使用标记化单词了。在

import spacy
s = 'hel-lo  this has whi(.)te, space. very \n good'
nlp = spacy.load('en') 
ls = [t.text for t in nlp(s) if t.text.strip()]

>> ['hel', '-', 'lo', 'this', 'has', 'whi(.)te', ',', 'space', '.', 'very', 'good']

然而,它也标记了-之间的单词,所以我借用了here的解决方案,将-之间的单词重新合并在一起。在

^{pr2}$
import re
s = 'hel-lo  this has whi(.)te, space. very \n good'
[x for x in re.split(r"([.,!?]+)?\s+", s) if x]
# => ['hel-lo', 'this', 'has', 'whi(.)te', ',', 'space', '.', 'very', 'good']

你可能需要调整什么是“标点符号”。在

我使用的是python3.6.1。在

import re

s = 'hel-lo  this has whi(.)te, space. very \n good'
a = [] # this list stores the items
for i in s.split(): # split on whitespaces
    j = re.split('(\,|\.)$',i) # split on your definition of trailing punctuation marks
    if len(j) > 1:
        a.extend(j[:-1])
    else:
        a.append(i)
 # a -> ['hel-lo', 'this', 'has', 'whi(.)te', ',', 'space', '.', 'very', 'good']

相关问题 更多 >