python - 如何在 Python 上使用正则表达式对文本进行标记而不忽略括号

标签 python regex nltk tokenize

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

例如:

我想标记这句话:

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/

相关文章:

javascript - 根据多个分隔符拆分字符串 [/, #, @, '' ]

python - python中的n-gram,四,五,六克?

python - python2.6应该使用OrderedDict的哪个实现?

python:为什么当我调用函数时它说 undefined variable ?

regex - 如何将 watch 命令输出解析为最后 5 位数字?

python - NLTK 无法找到 gs 文件

python - pandas dataframe python列中词频计数的输出不一致

python - 将 numpy 数组的列与另一个数组相加和相乘

python - 如何将树类对象结构序列化为JSON文件格式?

r - 从单独列的单词元素创建列