每5个空格后创建换行符

问题描述 投票:1回答:1

我有一个json文件中的字符串,我需要在每5个单词中插入一个\n。我尝试手动分割字符串的每5个字,但由于每次都是随机字符串,这是徒劳的。代码如下:

import tkinter as tk
from tkinter import *
import requests

root = tk.Tk()

root.resizable(width=False, height=False)

link = requests.get('https://talaikis.com/api/quotes/random/')
RESPONSE = link.json()['quote']   
RESPONSE2 = link.json()['author']
new = RESPONSE.split(" ")

l = []
l.append(sum(len(s) for s in new[0:5]))
l.append(sum(len(s) for s in new[5:10]))
l.append(sum(len(s) for s in new[10:15]))
l.append(sum(len(s) for s in new[15:20]))
l.append(sum(len(s) for s in new[20:25]))
l.append(sum(len(s) for s in new[25:30]))
l.append(sum(len(s) for s in new[30:35]))
l.append(sum(len(s) for s in new[35:40]))
l.append(sum(len(s) for s in new[40:45]))
l.append(sum(len(s) for s in new[45:50]))
l.append(sum(len(s) for s in new[50:55]))
x = list(set(l))
x.sort(reverse=True)

message = Label(root, text = RESPONSE + "\n-" + RESPONSE2, height=round(len(new)/5), width = x[0])
message.pack(side = tk.BOTTOM)
root.mainloop()

从整个列表的考验来看,在我试图找到最长的线时,它是非常非pythonic和一些丑陋的代码。我需要找到一种更快的方法来分割每5个单词。

python python-3.x tkinter
1个回答
1
投票

每当你看到弹出相同的模式时,总会出现一个循环。你的方法很好,但不是手动跳5,你可以举例如:

res = ''
for i in range(0,len(new),5):
    res += (' '.join(new[i:i+5]) + " \n ")

我不确定你想要聚合列表中的行然后排序,但你可以很容易地修改这个代码来做到这一点。

在Python中有很多方法可以做到这一点,更多的方法是Pyhtonic,但我认为这封装了解决方案的逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.