How to split a string into substrings with a fixed number of tokens and add the strings to a list? python
Question:
I would like to split a string into smaller (equal) parts of the string and save the substrings to a list.
Example:
text = 'This is an example text. I would like to split this text. End'
Output with substring with 3 words:
text_list = ['This is an', 'example text. I', 'would like to', 'split this text.', 'End']
Answers:
I guess this is one way to solve it:
def returnPartionedText(text: str, x: int = 3) -> list:
inputlist = text.split()
return([" ".join(inputlist[i:i + x]) for i in range(0, len(inputlist), x)])
text = 'This is an example text. I would like to split this text. End'
print(returnPartionedText(text))
Result:
['This is an', 'example text. I', 'would like to', 'split this text.', 'End']
NOTE: This will only work on text with spaces as it splits on that.
Other than that it’s pretty simple, it slices the text into list of lists and joins them in the end.
I would like to split a string into smaller (equal) parts of the string and save the substrings to a list.
Example:
text = 'This is an example text. I would like to split this text. End'
Output with substring with 3 words:
text_list = ['This is an', 'example text. I', 'would like to', 'split this text.', 'End']
I guess this is one way to solve it:
def returnPartionedText(text: str, x: int = 3) -> list:
inputlist = text.split()
return([" ".join(inputlist[i:i + x]) for i in range(0, len(inputlist), x)])
text = 'This is an example text. I would like to split this text. End'
print(returnPartionedText(text))
Result:
['This is an', 'example text. I', 'would like to', 'split this text.', 'End']
NOTE: This will only work on text with spaces as it splits on that.
Other than that it’s pretty simple, it slices the text into list of lists and joins them in the end.