用于拆分单词
str = "PYTHON IS VERY GOOD LANGUAGE CURRENTLY"
res = str.split(" ",2)
>> output: ["PYTHON", "IS", "VERY GOOD LANGUAGE CURRENTLY"]
但是如果我有这样的输出
output: ["PYTHON","IS VERY","GOOD LANGUAGE CURRENTLY"]
答案 0 :(得分:1)
在您的示例中,您似乎想将字符串拆分为包含1个单词,2个单词,3个单词等的子字符串列表。 我认为没有内置功能。但是,您可以使用以下代码来实现它:
if __name__ == '__main__':
str = "PYTHON IS VERY GOOD LANGUAGE CURRENTLY"
splits = str.split(" ") # Get string words
res = []
s = 0
i = 0
while s+1+i <= len(splits):
res.append(" ".join(splits[s:s+1+i])) # Make a string with i+1 words starting with word at index s
# Update your values
s+=i+1
i+=1
print(res)
['PYTHON', 'IS VERY', 'GOOD LANGUAGE CURRENTLY']
根据问题标题和评论者的理解,如果您的预期结果是["PYTHON IS", "VERY GOOD", " LANGUAGE CURRENTLY"]
,即由2个单词组成的字符串列表,那么它甚至会更容易。
str = "PYTHON IS VERY GOOD LANGUAGE CURRENTLY"
splits = str.split(" ")
# Zip one every two words starting from the beginning
# with one every two starting from second word
# leads to a list [(word1, word2), (word3, word4), ...]
# Join the tuples with a space, and build a list of these new strings
res = [" ".join(x) for x in zip(splits[::2], splits[1::2])]
print(res)
['PYTHON IS', 'VERY GOOD', 'LANGUAGE CURRENTLY']
答案 1 :(得分:0)
在python split()函数中,您有2个参数,分隔符和 maxsplit 。因此,如果您指定maxsplit,则只会拆分2,其余的字符串将不会拆分。
答案 2 :(得分:0)
您曾经说过split函数只能分裂两次
MAXSPLIT = 2
res = string.split(" ",MAXSPLIT) # Here, we are splitting 2 times.
# ['PYTHON', 'IS', 'VERY GOOD LANGUAGE CURRENTLY']
MAXSPLIT = 3
res = string.split(" ",3) # Here, we are splitting 3 times.
# ['PYTHON', 'IS', 'VERY', 'GOOD LANGUAGE CURRENTLY']
答案 3 :(得分:0)
这是一种稍作复杂的操作,它会产生一个列表列表,但是提取所需的输出并不难。我确定有人知道如何以更明智的方式做到这一点。我只使用str.split(“”)来创建原始字符串中的单词列表。
import numpy as np
def factorial_recursive(n):
if n == 0:
return n
elif n == 1:
return n
else:
return n+factorial_recursive(n-1)
str = "PYTHON IS VERY GOOD LANGUAGE CURRENTLY"
str_lst = str.split(" ")
start = 0
end = 1
output_list = []
for i in range(int(np.floor(len(str_lst)/2))):
if factorial_recursive(start) >= len(str_lst):
break
elif factorial_recursive(end) >= len(str_lst):
break
else:
output_list.append(str_lst[factorial_recursive(start):factorial_recursive(end)])
start += 1
end += 1
print(output_list)