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

rec*_*gle 58 python string words list text-segmentation

我正在尝试使用python将字符串转换为单词列表.我想采取以下内容:

string = 'This is a string, with words!'
Run Code Online (Sandbox Code Playgroud)

然后转换为这样的东西:

list = ['This', 'is', 'a', 'string', 'with', 'words']
Run Code Online (Sandbox Code Playgroud)

请注意省略标点符号和空格.最快的方法是什么?

Bry*_*yan 80

试试这个:

import re

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

这个怎么运作:

来自文档:

re.sub(pattern, repl, string, count=0, flags=0)
Run Code Online (Sandbox Code Playgroud)

返回通过替换repl替换字符串中最左边的非重叠模式而获得的字符串.如果未找到模式,则返回字符串不变.repl可以是字符串或函数.

所以在我们的情况下:

pattern是任何非字母数字字符.

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

a到z,A到Z,0到9和下划线.

所以我们匹配任何非字母数字字符并用空格替换它.

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

所以'你好世界'

成为'你好世界'

与re.sub

然后['你好','世界']

分裂后()

如果有任何疑问,请告诉我.

  • 您可能也想处理格式化的撇号和非断开连字符. (2认同)

小智 75

鉴于迟到的反应,我认为对于其他人来说,这是最简单的方法:

>>> string = 'This is a string, with words!'
>>> string.split()
['This', 'is', 'a', 'string,', 'with', 'words!']
Run Code Online (Sandbox Code Playgroud)

  • 您需要从单词中分离并消除标点符号(例如,"string"和"words!").因为它不符合OP的要求. (23认同)

Tim*_*ara 29

要做到这一点非常复杂.对于您的研究,它被称为单词标记化.如果你想看看别人做了什么,你应该看看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'.']
Run Code Online (Sandbox Code Playgroud)


JBe*_*rdo 16

最简单的方法:

>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'\w+', string)
['This', 'is', 'a', 'string', 'with', 'words']
Run Code Online (Sandbox Code Playgroud)


mtr*_*trw 14

使用string.punctuation的完整性:

import re
import string
x = re.sub('['+string.punctuation+']', '', s).split()
Run Code Online (Sandbox Code Playgroud)

这也处理新行.


Cam*_*ron 6

好吧,你可以用

import re
list = re.sub(r'[.!,;?]', ' ', string).split()
Run Code Online (Sandbox Code Playgroud)

请注意这两个stringlist是内建类型的名称,所以你可能不希望使用那些为您的变量名.


Pau*_*tas 6

受到@mtrw's answer 的启发,但改进后仅在单词边界处去除标点符号:

import re
import string

def extract_words(s):
    return [re.sub('^[{0}]+|[{0}]+$'.format(string.punctuation), '', w) for w in s.split()]

>>> str = 'This is a string, with words!'
>>> extract_words(str)
['This', 'is', 'a', 'string', 'with', 'words']

>>> str = '''I'm a custom-built sentence with "tricky" words like https://stackoverflow.com/.'''
>>> extract_words(str)
["I'm", 'a', 'custom-built', 'sentence', 'with', 'tricky', 'words', 'like', 'https://stackoverflow.com']
Run Code Online (Sandbox Code Playgroud)