我想知道如何实现一个函数get_words()
,它返回列表中字符串中的单词,去掉标点符号。
我希望如何实现它是将非 string.ascii_letters
替换为 ''
并返回一个 .split()
。
def get_words(text):
'''The function should take one argument which is a string'''
returns text.split()
例如:
>>>get_words('Hello world, my name is...James!')
返回:
>>>['Hello', 'world', 'my', 'name', 'is', 'James']
最佳答案
这与拆分和标点无关;你只关心字母(和数字),只需要一个正则表达式:
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
]
如果这是家庭作业,他们可能正在寻找一个命令式的东西,比如两态有限状态机,其中状态是“最后一个字符是字母”,如果状态从字母 -> 非字母变化,那么你输出一个词。不要那样做;这不是编程的好方法(尽管有时抽象很有用)。
关于python - 从字符串中提取单词,删除标点符号并返回带有分隔单词的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7633274/