我想我想做的是一项相当常见的任务,但我在网上找不到任何参考资料。我有带标点符号的文本,我想要一个单词列表。

"Hey, you - what are you doing here!?"

应该是

['hey', 'you', 'what', 'are', 'you', 'doing', 'here']

但Python的str.split()只对一个参数有效,所以在用空格拆分后,所有单词都带有标点符号。有什么想法吗?


当前回答

另一种方式,不使用正则表达式

import string
punc = string.punctuation
thestring = "Hey, you - what are you doing here!?"
s = list(thestring)
''.join([o for o in s if not o in punc]).split()

其他回答

试试看:

import re

phrase = "Hey, you - what are you doing here!?"
matches = re.findall('\w+', phrase)
print matches

这将打印['Hey','you','what','are','you','doing','here']

另一种方式,不使用正则表达式

import string
punc = string.punctuation
thestring = "Hey, you - what are you doing here!?"
s = list(thestring)
''.join([o for o in s if not o in punc]).split()

使用panda的series.str.split方法可以获得相同的结果,而不是使用re-module函数re.split。

首先,使用上述字符串创建一个系列,然后将该方法应用于该系列。

thestring=pd.Series(“嘿,你-你在这里干什么!?”)thestring.str.split(pat=',|-')

参数pat接受分隔符并将拆分字符串作为数组返回。这里,使用|(或运算符)传递两个分隔符。输出如下:

[嘿,你,你在这里干什么!?]

def get_words(s):
    l = []
    w = ''
    for c in s.lower():
        if c in '-!?,. ':
            if w != '': 
                l.append(w)
            w = ''
        else:
            w = w + c
    if w != '': 
        l.append(w)
    return l

用法如下:

>>> s = "Hey, you - what are you doing here!?"
>>> print get_words(s)
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']

re.split()

re.split(模式,字符串[,maxsplit=0])按模式的出现次数拆分字符串。如果模式中使用了捕获括号,那么模式中所有组的文本也会作为结果列表的一部分返回。如果maxsplit为非零,则最多发生maxsplit拆分,字符串的剩余部分将作为列表的最后一个元素返回。(不兼容注意:在最初的Python1.5版本中,maxsplit被忽略。这在以后的版本中得到了修复。)

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']