Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将字符串拆分为连续的、重叠的单词列表的最具python风格的方法是什么_Python_String_List - Fatal编程技术网

将字符串拆分为连续的、重叠的单词列表的最具python风格的方法是什么

将字符串拆分为连续的、重叠的单词列表的最具python风格的方法是什么,python,string,list,Python,String,List,假设我有一个句子“猫吃了老鼠。”我想用size=2来拆分这个句子 因此,结果数组变为: ["the cat", "cat ate", "ate the", "the mouse"] 如果我的尺码是3号,它应该是: ["the cat ate", "cat ate the", "ate the mouse"] 我现在使用的方法使用了大量for循环,我不确定是否有最好的方法。使用列表切片,您可以获得子列表 >>> words = "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循环,我不确定是否有最好的方法。

使用列表切片,您可以获得子列表

>>> words = "The cat ate the mouse.".rstrip('.').split()
>>> words[0:3]
['The', 'cat', 'ate']
用于将列表转换为由分隔符连接的字符串:

>>> ' '.join(words[0:3])
'The cat ate'
提供了创建单词列表的详细方法:

>>> 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]),...]


您可以使用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
是什么给了我们: (‘猫’、‘吃’) (‘猫’、‘吃’、‘那个’) (‘吃’、‘老鼠’) (“鼠标”、“鼠标”和“.”)

查找“python”