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

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

应该是

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

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


当前回答

我最喜欢替换方式。以下过程将字符串拆分列表中定义的所有分隔符更改为拆分列表中的第一个分隔符,然后在该分隔符上拆分文本。它还说明了splitlist是否恰好是空字符串。它返回一个单词列表,其中没有空字符串。

def split_string(text, splitlist):
    for sep in splitlist:
        text = text.replace(sep, splitlist[0])
    return filter(None, text.split(splitlist[0])) if splitlist else [text]

其他回答

遇到与@ooboo相同的问题并找到此主题@ghostdog74启发了我,也许有人觉得我的解决方案很有用

str1='adj:sg:nom:m1.m2.m3:pos'
splitat=':.'
''.join([ s if s not in splitat else ' ' for s in str1]).split()

在空格处输入内容,如果不想在空格处拆分,请使用相同的字符进行拆分。

这是一个有一些解释的答案。

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

# replace all the non alpha-numeric with space and then join.
new_string = ''.join([x.replace(x, ' ') if not x.isalnum() else x for x in st])
# output of new_string
'Hey  you  what are you doing here  '

# str.split() will remove all the empty string if separator is not provided
new_list = new_string.split()

# output of new_list
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']

# we can join it to get a complete string without any non alpha-numeric character
' '.join(new_list)
# output
'Hey you what are you doing'

或者在一行中,我们可以这样做:

(''.join([x.replace(x, ' ') if not x.isalnum() else x for x in st])).split()

# output
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']

更新的答案

首先,在循环中执行任何RegEx操作之前,请始终使用re.compile(),因为它的工作速度比正常操作快。

因此,对于您的问题,首先编译模式,然后对其执行操作。

import re
DATA = "Hey, you - what are you doing here!?"
reg_tok = re.compile("[\w']+")
print reg_tok.findall(DATA)

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

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

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

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

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

我遇到了类似的困境,不想使用“re”模块。

def my_split(s, seps):
    res = [s]
    for sep in seps:
        s, res = res, []
        for seq in s:
            res += seq.split(sep)
    return res

print my_split('1111  2222 3333;4444,5555;6666', [' ', ';', ','])
['1111', '', '2222', '3333', '4444', '5555', '6666']