【问题标题】:How do I tokenize a string sentence in NLTK?如何标记 NLTK 中的字符串句子?
【发布时间】:2013-02-10 01:32:07
【问题描述】:

我正在使用 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 允许我这样做。更重要的是,如何消除标点符号?

【问题讨论】:

  • 您能否澄清一下,underestimate punctation symbols 是什么意思?
  • 我认为他的意思是对输入的句子进行标记
  • 是的,例如如果我这样做了:sentente = "This is my sentence, a sentence is a short expression" 所以,'sentence' 和 'sentence' 将是两个不同的元素...

标签: python nlp tokenize nltk


【解决方案1】:

这个其实就在main page of 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', '.']

【讨论】:

  • 问题是它没有拆分/。如果你有“今天和/或明天是好日子”,它默认将“和/或”作为单个标记。
  • 我们如何将“n't”转换为“not”?
  • @Omayr,我会使用正则表达式将“n't”转换为“not”。我在下面附上了一些示例代码。 { re.sub("'t", 'ot', "n't, doesn't, can't, don't")} 粗体
  • 我在 Python2 中使用 word_tokenize,但在 Python3 中我想要一个字节列表,而不是字符串。有可能吗?
【解决方案2】:

正如@PavelAnossov 回答的,规范的答案,使用nltk 中的word_tokenize 函数:

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

【讨论】:

  • @pavel 的回答将解决诸如didn't -> did + n't 之类的问题
  • word_tokenize 有什么问题?看到这么多反对票,我想确保我没有错过任何东西。
  • 我没有投反对票,但我猜你的答案本质上是 Pavel 答案的副本。也许对他的回答发表评论会更合适。
猜你喜欢
  • 2012-12-15
  • 2014-12-31
  • 2015-07-22
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
相关资源
最近更新 更多