Как разбить длинные строки в python? - PullRequest
1 голос
/ 05 мая 2020

У меня есть список очень длинных строк, и я хочу знать, есть ли способ разделить каждый элемент строки определенным количеством слов, как на изображении внизу.

List = [“End extreme poverty in all forms by 2030”,
“End hunger, achieve food security and improved nutrition and promote sustainable agriculture”,
“Ensure healthy lives and promote well-being for all at all ages”,
“Ensure inclusive and equitable quality education and promote lifelong learning opportunities for all”,
 “Promote sustained, inclusive and sustainable economic growth, full and productive employment and decent work for all”]

Print(list)

Out:
“End extreme poverty in all forms by 2030”,

“End hunger, achieve food security and improved 
nutrition and promote sustainable agriculture”,

“Ensure healthy lives and promote well-being for all at all ages”,

“Ensure inclusive and equitable quality education and promote 
lifelong learning opportunities for all”,

 “Promote sustained, inclusive and sustainable economic growth, 
full and productive employment and decent work for all”]

окончательный результат похож на изображение

graphs showing long text wrapped

Ответы [ 2 ]

3 голосов
/ 05 мая 2020

Вы можете использовать textwrap:

import textwrap
print(textwrap.fill(List[1], 50))

End hunger, achieve food security and improved
nutrition and promote sustainable agriculture
1 голос
/ 05 мая 2020

Если вы хотите разбить его по количеству слов, вы можете:

Разделить строку на список слов:

my_list = my_string.split()

Затем вы можете разбить ее на K фрагменты, используя numpy:

import numpy as np
my_chunks = np.array_split(my_list , K) #K is number of chunks

Затем, чтобы вернуть фрагмент в строку, вы можете сделать:

my_string = " ".join(my_chunk[0])

Или, чтобы преобразовать их все в строки, вы можете сделать:

my_strings = list(map(" ".join, my_chunks))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...