将字符串转换为单词列表?

2024-04-19 13:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python将字符串转换为单词列表。我想买如下的东西:

string = 'This is a string, with words!'

然后转换成这样:

list = ['This', 'is', 'a', 'string', 'with', 'words']

注意省略了标点和空格。最快的办法是什么?


Tags: 字符串列表stringiswiththis单词list
3条回答

试试这个:

import re

mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ",  mystr).split()

工作原理:

从文档中:

re.sub(pattern, repl, string, count=0, flags=0)

返回字符串,该字符串通过替换repl替换字符串中最左边的模式不重叠的匹配项而获得。如果找不到模式,则返回字符串时保持不变。repl可以是字符串或函数。

所以在我们的案例中:

模式是任何非字母数字字符。

[\w]表示任何字母数字字符,等于字符集 [a-zA-Z0-9_u]

a到z,a到z,0到9和下划线。

因此我们匹配任何非字母数字字符并用空格替换。

然后我们split()它按空格分隔字符串并将其转换为列表

所以“你好,世界”

变成“你好世界”

带re.sub

然后['hello','world']

拆分后()

如果有任何疑问请告诉我。

我认为这是其他人在这个帖子上绊倒的最简单的方式,因为他们的回复很晚:

>>> string = 'This is a string, with words!'
>>> string.split()
['This', 'is', 'a', 'string,', 'with', 'words!']

要做到这一点是相当复杂的。对于您的研究,它被称为单词标记化。如果你想看看别人做了什么,而不是从头开始,你应该看看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'.']

相关问题 更多 >