如何在nltk中使用word_tokenize并保留空格?

Per*_*rry 1 nltk python-2.7

word_tokenize据我所知,nltk中的函数是一个字符串表示句子并返回其所有单词的列表:

>>> from nltk import word_tokenize, wordpunct_tokenize
>>> s = ("Good muffins cost $3.88\nin New York.  Please buy me\n"
...      "two of them.\n\nThanks.")
>>> word_tokenize(s) 
['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New', 'York.',
'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
Run Code Online (Sandbox Code Playgroud)

但是,在我的程序中,保留空间以进行进一步计算很重要,因此我宁愿word_tokenize像这样返回它:

['Good', ' ', 'muffins', ' ', 'cost', ' ', '$', '3.88', ' ', 'in', ' ', 'New', ' ', 'York.', ' ', 'Please', ' ', 'buy', ' ', 'me', ' ', 'two', ' ', 'of', ' ', 'them', '.', 'Thanks', '.' ]
Run Code Online (Sandbox Code Playgroud)

如何更改/替换/调整word_tokenize以实现此目的?

the*_*est 7

你可以分两步完成这项任务 -

步骤1:取出绳子并在空间的基础上进入

步骤2:使用标记每个单词(在步骤1中按空格分割) word_tokenize

>>> s = "Good muffins cost $3.88\nin New York.  Please buy me\n"
>>> ll = [[word_tokenize(w), ' '] for w in s.split()]
>>> list(itertools.chain(*list(itertools.chain(*ll))))
['Good', ' ', 'muffins', ' ', 'cost', ' ', '$', '3.88', ' ', 'in', ' ', 'New', ' ', 'York', '.', ' ', 'Please', ' ', 'buy', ' ', 'me', ' ']
Run Code Online (Sandbox Code Playgroud)