我尝试将字符串附加到字典中的列表中,以便每个参与者都有一个单词列表。这是我的密码:
words = [
{'word': 'we', 'start_time': 90, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': "haven't", 'start_time': 91, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': 'even', 'start_time': 91, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': 'spoken', 'start_time': 91, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': 'about', 'start_time': 92, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': 'your', 'start_time': 92, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': 'newest', 'start_time': 92, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
{'word': 'some word here', 'start_time': 45, 'participant': 'other user'}
]
words.sort(key=lambda x: x['start_time'])
clean_transcript = []
wordChunk = {'participant': '', 'words': []}
for w in words:
if wordChunk['participant'] == w['participant']:
wordChunk['words'].append(w['word'])
else:
wordChunk['participant'] = w['participant']
print(wordChunk['participant'])
wordChunk['words'].append(w['word'])
clean_transcript.append(wordChunk)
这给了我一个结果:
[{'participant': 'str_MIC_Y6E6_con_VnGhveZbaS', 'words': ['some word here', 'we', "haven't", 'even', 'spoken', 'about', 'your', 'newest']}]
所以some word here
在一个错误的列表中。我需要如何修改它来为other user
创建自己的单词列表
您可以使用itertools.groupby
输出:
使用列表理解
您可以重新构建数据结构,只需将其存储在参与者作为密钥的dict中:
wordChunk现在是一个dict,参与者作为键:
相关问题 更多 >
编程相关推荐