2017-05-14 4 views
1

文章があったと言います"The cat ate the mouse."文章をsize = 2で分割したいとします。文字列を連続して重複している単語リストに分割する最も平凡な方法は何ですか

だから、結果の配列は次のようになります。

["the cat", "cat ate", "ate the", "the mouse"] 

私のサイズが3だった場合、それはなるはず:

["the cat ate", "cat ate the", "ate the mouse"] 

私が持っている私の方法は、今のforループのトンを使用して、私はありません最善の方法があるかどうか確かめてください。

+1

"ngrams python"を参照してください。 –

答えて

3

リストスライスを使用すると、サブリストを取得できます。区切り文字によって接合された文字列にリストを変換する

>>> words = "The cat ate the mouse.".rstrip('.').split() 
>>> words[0:3] 
['The', 'cat', 'ate'] 

使用str.join

>>> ' '.join(words[0:3]) 
'The cat ate' 

List comprehensionの単語リストを作成するconside方法を提供します:

あなたが使用することができます
>>> n = 2 
>>> [' '.join(words[i:i+n]) for i in range(len(words) - n + 1)] 
['The cat', 'cat ate', 'ate the', 'the mouse'] 

>>> n = 3 
>>> [' '.join(words[i:i+n]) for i in range(len(words) - n + 1)] 
['The cat ate', 'cat ate the', 'ate the mouse'] 
# [' '.join(words[0:3]), ' '.join(words[1:4]),...] 

+0

yean、そうです。 –

0

すべての仕事をするnltkライブラリ

import nltk 
from nltk.util import ngrams 

text = "The cat ate the mouse." 
tokenize = nltk.word_tokenize(text) 
bigrams = ngrams(tokenize,3) 

for gram in bigrams: 
    print gram 

私たちを与えるもの: ( ''、 '猫'、 '食べた') ( '食べた'(、 '' '猫'、 '食べた') は、 ''、「マウス') (' the '、' mouse '、'。 ')

関連する問題