繁体   English   中英

如何用正则表达式将句子拆分为单词?

[英]How to split sentence to words with regular expression?

“她真好!” -> [“ she”,“'”,“ s”,“ so”,“ nice”,“!”]我想这样分割句子! 所以我写了代码,但是它包含空格! 如何仅使用正则表达式制作代码?

        words = re.findall('\W+|\w+')

-> [“ she”,“'”,“ s”,“”,“ so”,“”,“ nice”,“!”]

        words = [word for word in words if not word.isspace()]

正则表达式[A-Za-z]+|[^A-Za-z ]

[^A-Za-z ]添加您不想匹配的字符。

细节:

  • []匹配列表中存在的单个字符
  • [^]匹配列表中存在的单个字符
  • +无限次匹配
  • | 要么

Python代码

text = "She's so nice!"
matches = re.findall(r'[A-Za-z]+|[^A-Za-z ]', text)

输出:

['She', "'", 's', 'so', 'nice', '!']

代码演示

Python的re模块不允许您拆分零宽度的断言。 您可以改用python的pypi regex (确保您指定使用版本1,该版本可以正确处理零宽度匹配)。

在这里查看正在使用的代码

import regex

s = "She's so nice!"
x = regex.split(r"\s+|\b(?!^|$)", s, flags=regex.VERSION1)

print(x)

输出: ['She', "'", 's', 'so', 'nice', '!']

  • \\s+|\\b(?!^|$)匹配以下任一选项
    • \\s+匹配一个或多个空格字符
    • \\b(?!^|$)位置为单词边界,但不在行的开头或结尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM