[英]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.