将字符串转换为单词列表?
我想用Python把一个字符串转换成一个单词列表。我想处理的内容大概是这样的:
string = 'This is a string, with words!'
然后转换成这样的格式:
list = ['This', 'is', 'a', 'string', 'with', 'words']
注意这里去掉了标点符号和空格。请问有什么最快的方法来实现这个?
16 个回答
38
要做到这一点其实挺复杂的。这个过程在研究中被称为“词语切分”。如果你想看看别人是怎么做的,而不是从头开始,可以去看看NLTK。
>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second."
>>> sentences = nltk.sent_tokenize(paragraph)
>>> for sentence in sentences:
... nltk.word_tokenize(sentence)
[u'Hi', u',', u'this', u'is', u'my', u'first', u'sentence', u'.']
[u'And', u'this', u'is', u'my', u'second', u'.']
111
我觉得这是给其他看到这个帖子的人最简单的方法,尤其是考虑到我回复得比较晚:
>>> string = 'This is a string, with words!'
>>> string.split()
['This', 'is', 'a', 'string,', 'with', 'words!']
107
试试这个:
import re
mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ", mystr).split()
它是怎么工作的:
根据文档:
re.sub(pattern, repl, string, count=0, flags=0)
这个方法会返回一个字符串,它是通过把字符串中最左边的、不重叠的模式替换成指定的内容。如果找不到这个模式,字符串就会保持不变。替换的内容可以是一个字符串或者一个函数。
在我们的例子中:
模式是任何不是字母或数字的字符。
[\w]表示任何字母或数字的字符,它等同于字符集 [a-zA-Z0-9_]。
也就是说,它包括从a到z、从A到Z、从0到9和下划线。
所以我们匹配任何不是字母或数字的字符,并把它替换成一个空格。
然后我们用split()方法把字符串按空格分开,转换成一个列表。
比如说,'hello-world'
就变成了 'hello world'。
通过re.sub方法处理后,
最后得到 ['hello', 'world']
在调用split()之后。
如果有任何疑问,请告诉我。