dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
(1,"Do anything fun this weekend?"),(2,"I mostly slept"),
(2,"but I also played games"),(1,"That sounds fun")]
使用python,我正在尝试创建一个会话对数据集,其中集合中的每一对将具有扬声器1以及来自扬声器2的后续响应。 使用上面的示例数据,我需要遍历列表并1)合并来自同一发言者的句子(如果它们是后续的)2)创建该对,如下例所示;
输出:
((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))
如何编写一个接收这样的顺序数据的函数来创建会话对?
答案 0 :(得分:1)
conv = []
ls, lm = dat[0]
for s, m in dat[1:]:
if s == ls:
lm += ' ' + m
else:
conv.append((ls, lm))
ls, lm = s, m
else:
conv.append((ls, lm))
if conv[-1][0] == 1:
conv.append((2, None))
output = tuple([(conv[i], conv[i+1]) for i in range(0,len(conv) - 1, 2)])
输出:
[((1, 'hello how are you?'), (2, 'I am doing well, thanks!')), ((1, 'Do anything fun this weekend?'), (2, 'I mostly slept but I also played games')), ((1, 'That sounds fun'), (2, None))]
使用这段代码,希望这能解决您的目的
答案 1 :(得分:0)
def combine_speaker_lines(id_part_iter):
conversation = []
last_speaker, part = id_part_iter[0]
for speaker, fragment in id_part_iter[1:]:
if speaker != last_speaker:
conversation.append((last_speaker, part.lstrip()))
part = ''
part += ' ' + fragment
last_speaker = speaker
conversation.append((speaker, part.lstrip()))
return conversation
return conversation