如何在 Python 上使用正则表达式在不忽略括号的情况下标记文本

How to tokenize the text without ignoring their parenthesis using regex on Python

如何使用正则表达式在不忽略括号和 () 的情况下标记文本?

例如:

我想分词这个句子:

I don't like to eat Cici's food (it is true).

我使用了这个正则表达式:

pattern = r'''(?x)([A-Z]\.)+|\w+(-\w+)*|$?\d+(\.\d+)?%?|\.\.\.|[][.,;"'?():-_`]'''
tokenize_list = nltk.regexp_tokenize(sentence, pattern)

但是输出不是我想要的:

I
don
'
t
like
to
eat
Cici
'
s
food
(
it
is
true
)
.

我想要的输出应该是这样的,即考虑括号而不是标记化(以及它后面的一个词也不是标记化)和它之前的一个词:

I
don't
like
to
eat
Cici's
food
(it
is
true)
.

有人可以帮助我吗?谢谢。

您可以像这样使用正则表达式:

(['()\w]+|\.)

Working demo

比赛信息

MATCH 1
1.  [0-1]   `I`
MATCH 2
1.  [2-7]   `don't`
MATCH 3
1.  [8-12]  `like`
MATCH 4
1.  [13-15] `to`
MATCH 5
1.  [16-19] `eat`
MATCH 6
1.  [20-26] `Cici's`
MATCH 7
1.  [27-31] `food`
MATCH 8
1.  [32-35] `(it`
MATCH 9
1.  [36-38] `is`
MATCH 10
1.  [39-44] `true)`
MATCH 11
1.  [44-45] `.`