使用正则表达式划分两个单词并捕获第一个单词



以下词性标记句子:All/DT animals/NNS are/VBP equal/JJ ,/,但是/CC some/DT animals/NNS are/VBP more/RBR equal/JJ than/IN other/NNS ./.

如何编写仅匹配句子中每个单词/pos-tag 的单词的正则表达式。

text="""All/DT animals/NNS are/VBP equal/JJ ,/, but/CC some/DT animals/NNS 
are/VBP more/RBR equal/JJ than/IN others/NNS ./."""
tokens=nltk.word_tokenize(text)
pattern="([A-Za-z]+)|[A-Za-z]"
print("Upper case words:")
for tok in tokens:
   if re.search(pattern, tok) is not None:
      print("'{}'".format(tok))

使用 re.findall

import re
print (re.findall(r'([a-zA-Z]+)/[a-zA-Z]+',text))
#['All', 'animals', 'are', 'equal', 'but', 'some', 'animals', 'are', 'more', 'equal', 'than', 'others']
您可以使用

以下正则表达式:

(S+)/S+s?

解释:

(S+) 是匹配任何非空格字符
的捕获组 /匹配字符/
S+匹配非空格字符,但这次
未捕获 末尾
s?可选空间

这是一个测试正则表达式并获得解释的链接

正如@Transhuman建议的那样,使用 re.findall 获取所有匹配项:

import re
print (re.findall(r'(S+)/S+s?',text))

你可以在这里测试python代码:

最新更新