Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.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 用3个单词获取短语_Python_Text_Words - Fatal编程技术网

Python 用3个单词获取短语

Python 用3个单词获取短语,python,text,words,Python,Text,Words,我已经想了一段时间了 我想获取一个大文本/字符串,并将其拆分为3个单词的短语,然后将它们添加到数组中 我尝试过使用spilt(),但它没有像我希望的那样工作 我想做的是让它发挥作用: 从字符串中的前3个单词开始,当我得到这些单词时,我将其放入数组中,移动1个单词,然后取下3个单词,依此类推 这样做不好吗 亲切问候:) 第一行只代表您的字符串 在那之后,只要在空格上分开,假设这就是定义单词结尾的全部内容。(@andrew_reece关于边缘案例的评论非常相关。) 下一个函数在0到n-2的范围内迭代

我已经想了一段时间了

我想获取一个大文本/字符串,并将其拆分为3个单词的短语,然后将它们添加到数组中

我尝试过使用
spilt()
,但它没有像我希望的那样工作

我想做的是让它发挥作用:

从字符串中的前3个单词开始,当我得到这些单词时,我将其放入数组中,移动1个单词,然后取下3个单词,依此类推

这样做不好吗

亲切问候:)

第一行只代表您的字符串

在那之后,只要在空格上分开,假设这就是定义单词结尾的全部内容。(@andrew_reece关于边缘案例的评论非常相关。)

下一个函数在0到n-2的范围内迭代,其中n是字符串的长度。它从split_字符串数组中提取3个连续的单词,并用空格将它们连接起来

这几乎肯定不是最快的方法,因为它有一个拆分和一个联接,但它非常简单

>>> my_really_long_string = "this is a really long string"
>>> split_string = my_really_long_string.split()
>>> phrases = [" ".join(split_string[i:i+3]) for i in range(len(split_string) - 2)]
>>> 
>>> phrases
['this is a', 'is a really', 'a really long', 'really long string']
>>> 

这会奏效的。您可能希望首先剥离字符文本,但不确定数据是什么

x = 'alt bot cot dot eat fat got hot iot jot kot lot mot not'
x = [y for y in [x.strip().split(' ')[i:i+3] for i in range(0, len(x), 3)]]

有各种各样的NLP包提供三元语法分析,例如
nltk
。使用其中一个可以节省一些精力。(如果你想自己实际构建一个三元语法分析器,请提供一个具体的例子,包括如何处理标点、数字等边缘情况,以及预期的输出。)感谢@andrew_reece为你提供的关于NLTK的信息,在某个时候我将改变我这样做的方式,现在我只是想找出最简单的解决办法。谢谢:)这正是我所需要的。现在我只需要从tekst中去掉所有逗号、标点符号等,这样我就只得到干净的文本。非常感谢Scott,非常感谢您的输入:)我现在开始工作了,现在我只需要清理我得到的html:)hjælpen的Såmange tak:)Ved du endelig om der findes nogle danske python for ummer påFB?,har kigget men ike fundet nogle endnu。与我的区别在于它生成了一个列表。
x = 'alt bot cot dot eat fat got hot iot jot kot lot mot not'
x = [y for y in [x.strip().split(' ')[i:i+3] for i in range(0, len(x), 3)]]