python 中的 n-gram,四、五、六克?

新手上路,请多包涵

我正在寻找一种将文本拆分为 n-gram 的方法。通常我会做类似的事情:

 import nltk
from nltk import bigrams
string = "I really like python, it's pretty awesome."
string_bigrams = bigrams(string)
print string_bigrams

我知道 nltk 只提供双字母组和三字母组,但有没有办法将我的文本分成四克、五克甚至一百克?

谢谢!

原文由 Shifu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 393
2 个回答

其他用户给出的基于原生 python 的出色答案。但这是 nltk 方法(以防万一,OP 因重新发明 nltk 库中已经存在的内容而受到惩罚)。

nltk 中有一个人们很少使用的 ngram模块。这不是因为 ngram 很难阅读,而是基于 n > 3 的 ngram 训练模型会导致大量数据稀疏。

 from nltk import ngrams

sentence = 'this is a foo bar sentences and i want to ngramize it'

n = 6
sixgrams = ngrams(sentence.split(), n)

for grams in sixgrams:
  print grams

原文由 alvas 发布,翻译遵循 CC BY-SA 4.0 许可协议

我很惊讶这还没有出现:

 In [34]: sentence = "I really like python, it's pretty awesome.".split()

In [35]: N = 4

In [36]: grams = [sentence[i:i+N] for i in xrange(len(sentence)-N+1)]

In [37]: for gram in grams: print gram
['I', 'really', 'like', 'python,']
['really', 'like', 'python,', "it's"]
['like', 'python,', "it's", 'pretty']
['python,', "it's", 'pretty', 'awesome.']

原文由 inspectorG4dget 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题