python - 正则表达式模式在剥离结束标点符号的同时标记句子?
问题描述
我需要制作一个正则表达式模式,它可以标记一个句子,除了首字母缩写词、缩写词和连字符之外,它还分别标记了标点符号。
"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 所提到的,如果没有自然语言工具包,这是徒劳的练习。
此正则表达式可以匹配两种情况:
[^\s.]{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'
'.'
推荐阅读
- lotus-domino - “磁盘空间不足:~tmpview.tmp”如何解决?
- angular6 - Angular-6 路由器出口不是已知元素,模板解析错误
- antlr4 - 为什么 C++ 目标比 Java 目标慢 6 倍
- javascript - 如何验证 Nuxt 中的路由参数?
- javascript - 即使在我的页面上执行提交或重置等功能后,如何保持背景图像切换
- python - Python - 将列表作为参数传递给类
- linux - | 中的字符串值 分隔字段在 awk 中向右拆分
- java - 我无法弄清楚缺少什么格式项目
- java - Spring Boot 2.0.5 是否不运行请求参数
- c# - 如何在计时器运行时实时更改计时器剩余的时间?