Jam*_*ith 17 python string list
我想知道如何实现一个函数get_words(),返回列表中的字符串中的单词,剥离标点符号.
我多么想拥有它实行的是取代不可string.ascii_letters用'',并返回.split().
def get_words(text):
'''The function should take one argument which is a string'''
returns text.split()
Run Code Online (Sandbox Code Playgroud)
例如:
>>>get_words('Hello world, my name is...James!')
Run Code Online (Sandbox Code Playgroud)
收益:
>>>['Hello', 'world', 'my', 'name', 'is', 'James']
Run Code Online (Sandbox Code Playgroud)
nin*_*cko 37
这与分裂和标点符号无关; 你只关心字母(和数字),只想要一个正则表达式:
import re
def getWords(text):
return re.compile('\w+').findall(text)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> re.compile('\w+').findall('Hello world, my name is...James the 2nd!')
['Hello', 'world', 'my', 'name', 'is', 'James', 'the', '2nd']
Run Code Online (Sandbox Code Playgroud)
如果您不关心数字,替换\w用[A-Za-z]的只是文字,或[A-Za-z']包括收缩等可能有奇的方法,包括字母,非数字字符类(如带有重音字母)与其他正则表达式.
我几乎在这里回答了这个问题:Split Strings with Multiple Delimiters?
但你的问题实际上是不明确的:你想'this is: an example'分成:
['this', 'is', 'an', 'example']['this', 'is', 'an', '', 'example']?我以为这是第一个案例.
[这个','是','一个',例子']是我想要的.有没有导入正则表达式的方法?如果我们可以用''替换非ascii_letters,然后将字符串拆分成列表中的单词,那会有效吗? - 詹姆斯史密斯2分钟前
正则表达式是最优雅的,但是,你可以这样做如下:
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()
Run Code Online (Sandbox Code Playgroud)
要么 .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
]
Run Code Online (Sandbox Code Playgroud)
如果这是作业,他们可能正在寻找像两状态有限状态机这样的命令式事情,其中状态是"是字母的最后一个字符",如果状态从字母改变 - >非字母然后输出字.不要那样做; 它不是一个好的编程方式(尽管有时抽象很有用).
Rom*_*huk 11
尝试使用re:
>>> [w for w in re.split('\W', 'Hello world, my name is...James!') if w]
['Hello', 'world', 'my', 'name', 'is', 'James']
Run Code Online (Sandbox Code Playgroud)
虽然我不确定它会抓住你所有的用例.
如果要以其他方式解决它,可以指定要在结果中出现的字符:
>>> re.findall('[%s]+' % string.ascii_letters, 'Hello world, my name is...James!')
['Hello', 'world', 'my', 'name', 'is', 'James']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46719 次 |
| 最近记录: |