这与分裂和标点符号无关;你只关心字母(和数字),只想要一个正则表达式:
import re
def getWords(text)
return re.compile('\w+').findall(text)演示:
>>> re.compile('\w+').findall('Hello world, my name is...James the 2nd!')
['Hello', 'world', 'my', 'name', 'is', 'James', 'the', '2nd']如果您不关心数字,请将\w替换为[A-Za-z]仅用于字母,或将[A-Za-z']替换为包括收缩等。可能有更好的方法将字母非数字字符类(例如带有重音符号的字母)与其他正则表达式包括在内。
我几乎在这里回答了这个问题:Split Strings with Multiple Delimiters?
但是你的问题实际上没有说明:你想把'this is: an example'分成:
['this', 'is', 'an', 'example']
或['this', 'is', 'an', '', 'example']?
我认为这是第一个案例。
[this', 'is', 'an', example'] is what i want. is there a method without importing regex? If we can just replace the non ascii_letters with '', then splitting the string into words in a list, would that work? – James Smith 2 mins ago
正则表达式是最优雅的,但是,你可以这样做如下:
def getWords(text):
"""
Returns a list of words, where a word is defined as a
maximally connected substring of uppercase or lowercase
alphabetic letters, as defined by "a".isalpha()
>>> get_words('Hello world, my name is... Élise!') # works in python3
['Hello', 'world', 'my', 'name', 'is', 'Élise']
"""
return ''.join((c if c.isalnum() else ' ') for c in text).split()或.isalpha()
旁注:您也可以执行以下操作,但需要导入另一个标准库:
from itertools import *
# groupby is generally always overkill and makes for unreadable code
# ... but is fun
def getWords(text):
return [
''.join(chars)
for isWord,chars in
groupby(' My name, is test!', lambda c:c.isalnum())
if isWord
]
如果这是家庭作业,他们可能正在寻找像两状态有限状态机这样的命令式事物,其中状态是“字母的最后一个字符”,如果状态从字母 - >非字母改变,则输出一个字。不要那样做;它不是一个好的编程方式(尽管有时抽象很有用)。