用3个单词来获取短语

2024-09-28 21:59:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想弄清楚这个问题已经有一段时间了。你知道吗

我想把一个大的文本/字符串拆分成3个单词的短语,并将它们添加到一个数组中。你知道吗

我试过使用spilt(),但没有如我所希望的那样工作。你知道吗

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

从字符串中的前3个单词开始,当我得到它们时,我把它放入一个数组中,移动1个单词,然后取下3个单词,依此类推。你知道吗

这样做不好吗?你知道吗

谨致问候:)


Tags: 字符串文本数组单词问候发挥作用spilt
2条回答
my_really_long_string = "this is a really long string"
split_string = my_really_long_string.split()
phrase_array = [" ".join(split_string[i:i+3]) for i in range(len(split_string) - 2)]

第一行只是表示字符串。你知道吗

在那之后,就把空格分开,假设你只关心定义单词的结尾。(@andrew_reece对边缘案件的评论非常相关。)

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

这几乎肯定不是最快的方法,因为它有一个split和一个join,但是它非常简单。你知道吗

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

相关问题 更多 >