gpt4 book ai didi

python - 如何在每第 n 次出现空格但重叠时拆分字符串

转载 作者:行者123 更新时间:2023-12-04 19:25:17 25 4
gpt4 key购买 nike

我有一个字符串:

Your dog is running up the tree.

我希望能够在每个第 k 个空间上分割它但有重叠。例如,每隔一个空间:
Your dog is running up the tree.
out = ['Your dog', 'dog is', 'is running', 'running up', 'up the', 'the tree']

每隔一个空间:
Your dog is running up the tree.
out = ['Your dog is', 'dog is running', 'is running up', 'running up the', 'up the tree']

我知道我可以做类似的事情
>>> i=iter(s.split('-'))                  
>>> map("-".join,zip(i,i))

但这不适用于我想要的重叠。有任何想法吗?

最佳答案

我建议先在每个空格处拆分,然后在迭代列表时将所需数量的单词重新组合在一起

s = 'Your dog is running up the tree.'
lst = s.split()

def k_with_overlap(lst, k):
return [' '.join(lst[i:i+k]) for i in range(len(lst) - k + 1)]

k_with_overlap(lst, 2)

['Your dog', 'dog is', 'is running', 'running up', 'up the', 'the tree.']

关于python - 如何在每第 n 次出现空格但重叠时拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com