我正在尝试对以下数组进行文本对齐并将其转换为如图所示的聊天系统。到目前为止,我能够正确对齐,但我一直试图让它看起来像一个聊天对话
“1”、“2”表示用户和他们的消息,数组应确定对齐的交替顺序。宽度是一行的总宽度,用户宽度是用户在一行中可以采取的最大宽度。用户 1 左对齐,用户 2 右对齐。
到目前为止,我有以下代码:
messages = [["1", "Bob hello"], ["2", "Alice hi"], ["1", "How is your life"], ["1", "Better than before"],
["2", "M super"], ["1", "Wow pro"]]
userWidth = 6
width = 15
def chat(messages, userWidth, width):
user1 = []
user2 = []
sep_num = []
order = []
for message in messages:
user = message[0]
convo = message[1]
windowStart = 0
sep_num.append(len(convo) // userWidth + 1)
order.append(user)
for windowEnd in range(len(convo)):
if windowEnd > 0:
if (windowEnd + 1) % userWidth == 0:
if user == "1":
left_aligned = convo[windowStart:windowEnd + 1]
user1.append(left_aligned)
else:
right_aligned = convo[windowStart:windowEnd + 1]
user2.append(right_aligned)
windowStart = windowEnd + 1
if windowEnd == len(convo) - 1:
if user == "1":
left_aligned = convo[windowStart:windowEnd + 1]
if len(left_aligned) == 1 and user1[-1][-3] != " ":
left_aligned = "".join([user1[-1][-1],left_aligned])
user1[-1] = user1[-1][:-1]
if len(left_aligned) == 1 and user1[-1][-3] == " ":
left_aligned = "".join([user1[-1][-3:], left_aligned])
user1[-1] = user1[-1][:-3]
user1.append(left_aligned)
else:
right_aligned = convo[windowStart:windowEnd + 1]
if len(right_aligned) == 1 and user2[-1][-3] != " ":
right_aligned = "".join([user2[-1][-1], right_aligned])
user2[-1] = user2[-1][:-1]
if len(right_aligned) == 1 and user1[-1][-3] == " ":
right_aligned = "".join([user1[-1][-3:], right_aligned])
user1[-1] = user1[-1][:-3]
user2.append(right_aligned)
constructor(user1, user2, width, order, sep_num)
def constructor(user1, user2, width, order, sep_num):
for i in range(len(user1)):
if (len(user1[i])) > 1:
if user1[i][0] == " ":
user1[i] = user1[i][1:]
space = width - len(user1[i])
line = "|" + user1[i] + (" " * space)
print(line)
for i in range(len(user2)):
if (len(user2[i])) > 1:
if user2[i][-1] == " ":
user2[i] = user2[i][:-1]
space = width - len(user2[i])
line = (" " * space) + user2[i] + "|"
print(line)
这使它看起来像这样:
|Bob he
|llo
|How is
|your
|life
|Better
|than
|before
|Wow
|pro
Alice|
hi|
M sup|
er|
但是我怎样才能将其转换为以下内容: