如何使用正则表达式在不忽略括号和 () 的情况下标记文本?
例如:
我想标记这句话:
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] `.`
关于python - 如何在 Python 上使用正则表达式对文本进行标记而不忽略括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995802/