89

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

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

然后转换成这样的东西:

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

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

4

15 回答 15

105

试试这个:

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 替换 string 中最左边的不重叠出现的模式获得的字符串。如果未找到该模式,则字符串原封不动地返回。repl 可以是字符串或函数。

所以在我们的例子中:

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

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

a 到 z、A 到 Z、0 到 9 和下划线。

所以我们匹配任何非字母数字字符并将其替换为空格。

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

所以“你好世界”

变成“你好世界”

与 re.sub

然后 ['hello' , 'world']

拆分后()

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

于 2011-05-31T00:13:53.553 回答
104

鉴于迟到的回应,我认为这是其他人绊倒这篇文章的最简单方法:

>>> string = 'This is a string, with words!'
>>> string.split()
['This', 'is', 'a', 'string,', 'with', 'words!']
于 2012-12-06T00:22:28.463 回答
36

要正确地做到这一点是相当复杂的。对于您的研究,它被称为词标记化。如果你想看看其他人做了什么,你应该看看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'.']
于 2011-05-31T00:15:21.240 回答
20

最简单的方法:

>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'\w+', string)
['This', 'is', 'a', 'string', 'with', 'words']
于 2011-05-31T02:19:14.940 回答
15

使用string.punctuation完整性:

import re
import string
x = re.sub('['+string.punctuation+']', '', s).split()

这也处理换行符。

于 2011-05-31T00:24:02.343 回答
8

好吧,你可以使用

import re
list = re.sub(r'[.!,;?]', ' ', string).split()

请注意,stringlist都是内置类型的名称,因此您可能不想将它们用作变量名称。

于 2011-05-31T00:10:30.163 回答
6

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

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']
于 2017-06-08T09:55:37.863 回答
3

单词的正则表达式将为您提供最大的控制权。您需要仔细考虑如何处理带有破折号或撇号的单词,例如“I'm”。

于 2011-05-31T00:14:40.857 回答
3

就个人而言,我认为这比提供的答案稍微干净一些

def split_to_words(sentence):
    return list(filter(lambda w: len(w) > 0, re.split('\W+', sentence))) #Use sentence.lower(), if needed
于 2018-05-18T05:47:09.293 回答
1
list=mystr.split(" ",mystr.count(" "))
于 2015-08-11T15:14:35.827 回答
1

这样您就可以消除字母表之外的每个特殊字符:

def wordsToList(strn):
    L = strn.split()
    cleanL = []
    abc = 'abcdefghijklmnopqrstuvwxyz'
    ABC = abc.upper()
    letters = abc + ABC
    for e in L:
        word = ''
        for c in e:
            if c in letters:
                word += c
        if word != '':
            cleanL.append(word)
    return cleanL

s = 'She loves you, yea yea yea! '
L = wordsToList(s)
print(L)  # ['She', 'loves', 'you', 'yea', 'yea', 'yea']

我不确定这是否是快速或最佳的,甚至是正确的编程方式。

于 2017-07-30T15:22:07.277 回答
1
def split_string(string):
    return string.split()

此函数将返回给定字符串的单词列表。在这种情况下,如果我们如下调用函数,

string = 'This is a string, with words!'
split_string(string)

该函数的返回输出将是

['This', 'is', 'a', 'string,', 'with', 'words!']
于 2022-02-04T12:43:01.167 回答
0

这是我对无法使用正则表达式的编码挑战的尝试,

outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')

撇号的作用似乎很有趣。

于 2015-05-28T06:30:26.143 回答
0

可能不是很优雅,但至少你知道发生了什么。

my_str = "Simple sample, test! is, olny".lower()
my_lst =[]
temp=""
len_my_str = len(my_str)
number_letter_in_data=0
list_words_number=0
for number_letter_in_data in range(0, len_my_str, 1):
    if my_str[number_letter_in_data] in [',', '.', '!', '(', ')', ':', ';', '-']:
        pass
    else:
        if my_str[number_letter_in_data] in [' ']:
            #if you want longer than 3 char words
            if len(temp)>3:
                list_words_number +=1
                my_lst.append(temp)
                temp=""
            else:
                pass
        else:
            temp = temp+my_str[number_letter_in_data]
my_lst.append(temp)
print(my_lst)
于 2021-03-15T20:03:30.983 回答
-1

您可以尝试这样做:

tryTrans = string.maketrans(",!", "  ")
str = "This is a string, with words!"
str = str.translate(tryTrans)
listOfWords = str.split()
于 2013-08-12T13:49:25.417 回答