将文本从文本拆分为Python中的nGrams

时间:2016-07-10 11:19:31

标签: python python-2.7 python-3.x

我必须将文本文件拆分为列表中每个列表的特定数量的单词,最好在示例中显示。

说文本文件看起来像这样

ngrams.makeNGrams("ngrams.txt", 2)
#so since the given variable says 2 the output should look like this:

[['i', 'am'],['am', 'having'],['having', 'a'],['a',’good’],[’good’, ’day’],[’day’,’today’]]

我必须编写一个看起来像这样的函数

ngrams.makeNGrams("ngrams.txt", 3)

#it should give out:

[[’i’,’am’,’having’],[’having’,’a’,’good’],[’good’,’day’,’today’]]

如果函数看起来像这样

<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                root_path, :class => 'btn btn-default' %>

现在有人应该如何处理这个问题吗? 非常感谢提前

3 个答案:

答案 0 :(得分:1)

我会这样做:

def ngrams(words, n):
    return zip(*(words[i:] for i in range(n)))

用法:

>>> words = "i am having a good day today".split()
>>> list(ngrams(words, 2))
[('i', 'am'), ('am', 'having'), ('having', 'a'), ('a', 'good'), ('good', 'day'), ('day', 'today')]
>>> list(ngrams(words, 3))
[('i', 'am', 'having'), ('am', 'having', 'a'), ('having', 'a', 'good'), ('a', 'good', 'day'), ('good', 'day', 'today')]

我们的想法是从原始列表生成n个列表,第i个列表移动i。然后只需zip将这些移位列表放在一起并返回结果。

n=3的可视化:

['i',      'am',     'having', 'a',    'good', 'day', 'today']  # not shifted
['am',     'having', 'a',      'good', 'day',  'today']         # shifted by 1
['having', 'a',      'good',   'day',  'today']                 # shifted by 2

zip函数将元素以相同的索引缝合在一起,直到最短的列表用完为止,产生所需的输出。

答案 1 :(得分:0)

定义:

def ngrams(text, n):
    words = text.split()
    return [ words[i:i+n] for i in range(len(words)-n+1) ]

并使用:

s = "i am having a good day today"
ngrams(s, 2)

答案 2 :(得分:0)

我确信有更多的pythonic方法可以做到这一点。它不是一个功能(但它应该很容易适应),而是一个程序。我认为它遵循您的规范:

import sys

num = int(sys.argv[1])

cad = "i am having a good day today"

listCad =  cad.split(" ")

listOfLists = []
i = 0
while i <= len(listCad) - num:
   listOfLists.append(listCad[i:i+num])
   i = i + (num - 1)

print listOfLists