如何在NLTK中对字符串句子进行分词?

67 投票
2 回答
157838 浏览
提问于 2025-04-17 16:59

我正在使用nltk这个库,所以我想创建自己的文本,跟nltk.books里面的默认文本一样。不过,我现在只知道一些方法,比如:

my_text = ['This', 'is', 'my', 'text']

我想知道有没有办法把我的“文本”输入成:

my_text = "This is my text, this is a nice way to input text."

哪种方法,Python的还是nltk的,可以让我做到这一点?更重要的是,我该怎么去掉标点符号呢?

2 个回答

-7

正如 @PavelAnossov 所说,标准的答案是使用 word_tokenize 函数,这个函数在 nltk 库里:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

如果你的句子真的很简单:

可以使用 string.punctuation 这个集合,先去掉标点符号,然后再用空格来分割句子:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y
169

这实际上是在 nltk.org 的主页上:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

撰写回答