我编写了一个tokenize函数,它基本上读取字符串表示并将其拆分为单词列表。
我的代码:
def tokenize(document):
x = document.lower()
return re.findall(r'\w+', x)我的产出:
tokenize("Hi there. What's going on? first-class")
['hi', 'there', 'what', 's', 'going', 'on', 'first', 'class']期望产出:
['hi', 'there', "what's", 'going', 'on', 'first-class']基本上,我希望撇号词和下流词与双引号一起保持为单字。如何更改我的函数以获得所需的输出。
发布于 2015-02-04 00:41:48
\w+匹配一个或多个单词字符;这不包括撇号或连字符。
您需要在这里使用一个字符集来告诉Python您想要匹配的是什么:
>>> import re
>>> def tokenize(document):
... return re.findall("[A-Za-z'-]+", document)
...
>>> tokenize("Hi there. What's going on? first-class")
['hi', 'there', "what's", 'going', 'on', 'first-class']
>>>您也会注意到,我删除了x = document.lower()行。这不再是必要的,因为我们可以通过简单地将A-Z添加到字符集来匹配大写字符。
https://stackoverflow.com/questions/28311491
复制相似问题