简体   繁体   English

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

[英]Tokenize based on white space and trailing punctuation?

I'm trying to come up with the regular expression to split a string up into a list based on white space or trailing punctuation. 我正在尝试提出正则表达式,以根据空格或尾随标点将字符串分成列表。

eg 例如

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

What I want is 我想要的是

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

s.split() gets me most of the way there, except it doesn't take care of the trailing whitespace. s.split()可以帮助我解决大部分问题,只是它不会处理尾随的空格。

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

You might need to tweak what "punctuation" is. 您可能需要调整什么是“标点符号”。

Rough solution using spacy . 使用spacy粗略解决方案。 It works pretty good with tokenizing word already. 它已经可以对单词进行分词了。

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

However, it also tokenize words between - so I borrow solution from here to merge words between - back together. 然而,它也与记号化的话-所以我借的解决方案,从这里到合并之间的话-重新走到一起。

merge = [(i-1, i+2) for i, s in enumerate(ls) if i >= 1 and s == '-']
for t in merge[::-1]:
    merged = ''.join(ls[t[0]:t[1]])
    ls[t[0]:t[1]] = [merged]

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

I am using Python 3.6.1. 我正在使用Python 3.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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM