我想我想做的是一项相当常见的任务,但我在网上找不到任何参考资料。我有带标点符号的文本,我想要一个单词列表。
"Hey, you - what are you doing here!?"
应该是
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
但Python的str.split()只对一个参数有效,所以在用空格拆分后,所有单词都带有标点符号。有什么想法吗?
我想我想做的是一项相当常见的任务,但我在网上找不到任何参考资料。我有带标点符号的文本,我想要一个单词列表。
"Hey, you - what are you doing here!?"
应该是
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
但Python的str.split()只对一个参数有效,所以在用空格拆分后,所有单词都带有标点符号。有什么想法吗?
当前回答
首先,在循环中执行任何RegEx操作之前,请始终使用re.compile(),因为它的工作速度比正常操作快。
因此,对于您的问题,首先编译模式,然后对其执行操作。
import re
DATA = "Hey, you - what are you doing here!?"
reg_tok = re.compile("[\w']+")
print reg_tok.findall(DATA)
其他回答
实现这一点的另一种方法是使用自然语言工具包(nltk)。
import nltk
data= "Hey, you - what are you doing here!?"
word_tokens = nltk.tokenize.regexp_tokenize(data, r'\w+')
print word_tokens
这张照片显示:[“嘿”、“你”、“什么”、“是”、“您”、“正在做”、“在这里”]
这种方法的最大缺点是需要安装nltk包。
好处是,一旦获得令牌,就可以使用nltk包的其余部分做很多有趣的事情。
在Python3中,您可以使用PY4E-PythonforEveryone中的方法。
我们可以通过使用字符串方法lower、标点符号和translate来解决这两个问题。翻译是最微妙的方法。以下是翻译文档:
your_string.translate(your_string.maketrans(fromstr,tostr,deletestr))
将fromstr中的字符替换为tostr中相同位置的字符,并删除deletestr中的所有字符。fromstr和tostr可以是空字符串,并且可以省略deletestr参数。
您可以看到“标点符号”:
In [10]: import string
In [11]: string.punctuation
Out[11]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
例如:
In [12]: your_str = "Hey, you - what are you doing here!?"
In [13]: line = your_str.translate(your_str.maketrans('', '', string.punctuation))
In [14]: line = line.lower()
In [15]: words = line.split()
In [16]: print(words)
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
有关详细信息,请参阅:
PY4E-面向每个人的Python字符串转换str.maketransPython字符串maketrans()方法
我认为以下是满足您需求的最佳答案:
\W+可能适合这种情况,但可能不适合其他情况。
filter(None, re.compile('[ |,|\-|!|?]').split( "Hey, you - what are you doing here!?")
创建一个函数,将两个字符串(要拆分的源字符串和分隔符的拆分列表字符串)作为输入,并输出拆分单词列表:
def split_string(source, splitlist):
output = [] # output list of cleaned words
atsplit = True
for char in source:
if char in splitlist:
atsplit = True
else:
if atsplit:
output.append(char) # append new word after split
atsplit = False
else:
output[-1] = output[-1] + char # continue copying characters until next split
return output
我喜欢pprzemek的解决方案,因为它不假设分隔符是单个字符,也不试图利用正则表达式(如果分隔符的数量太长,这将不会很好地工作)。
为清晰起见,以下是上述解决方案的更可读版本:
def split_string_on_multiple_separators(input_string, separators):
buffer = [input_string]
for sep in separators:
strings = buffer
buffer = [] # reset the buffer
for s in strings:
buffer = buffer + s.split(sep)
return buffer