python - 正则表达式模式在剥离结尾标点符号的同时标记句子?

标签 python regex

我需要制作一个正则表达式模式,可以标记一个句子,并且还可以单独标记标点符号,首字母缩略词、缩写词和连字符除外。

"This is a test sentence. I won't write this sentence. J. Smith lives in the U.S.A. and it is nice there."

应返回为

["This" "is" "a" "test" "sentence" "." "I" "won't" "write" "this" "sentence" "." "J." "Smith" "lives" 
 "in" "the" "U.S.A." "and" "it" "is" "nice" "there" ."]

我当前的代码是:

tokens = re.findall(r'((\.\s)|(\S+))', sentence)

但这不能正常工作。它匹配单词末尾的句号作为单词的一部分。

最佳答案

您可以使用 [^\s.]{2,}|(?:\w|\.)+ 来标记这个特定的示例,但正如 Ryan 提到的,没有自然语言工具包,这是徒劳的做法。

此正则表达式可以匹配两种情况:

  1. [^\s.]{2,} 匹配 2 个或多个连续的非空格、非文字句点字符
  2. (?:\w|\.)+ 匹配一个或多个连续的单词字符或文字句点

用法:

import re

s = """This is a test sentence. 
I won't write this sentence. J. Smith lives in the U.S.A.  and it is nice there.
"""

for token in re.findall(r"[^\s.]{2,}|(?:\w|\.)+", s):
    print(repr(token))

输出:

'This'
'is'
'a'
'test'
'sentence'
'.'
'I'
"won't"
'write'
'this'
'sentence'
'.'
'J.'
'Smith'
'lives'
'in'
'the'
'U.S.A.'
'and'
'it'
'is'
'nice'
'there'
'.'

关于python - 正则表达式模式在剥离结尾标点符号的同时标记句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60291136/

相关文章:

用其他东西替换字符串中第 N 次出现的字符

PHP - 用于删除所有事件属性的正则表达式

regex - 搜索多个连续字符并替换为单个字符,同时排除某些字符

javascript - 正则表达式删除任何不是数字或特定单词的内容

python - 将多个 id 传递到 url Django

Python:使用 PIL 加载 png 文件给出奇怪的结果

python - 类型错误 : 'numpy.float64' object cannot be interpreted as an integer and casting to int fails

python - Django 中图像/头像的自定义保存方法 - 如何使用

python - 如何在没有互联网连接的情况下在 CentOS 中安装最新版本的 Python 和 python 包?

regex - 使用电子邮件地址作为用户名的正则表达式?