gpt4 book ai didi

python - 基于列表反汇编和重新组装字符串

转载 作者:行者123 更新时间:2023-11-30 23:05:24 25 4
gpt4 key购买 nike

我有四个这样的扬声器:

Team_A=[弗雷德,鲍勃]

Team_B=[约翰, jack ]

他们正在进行对话,并且全部由字符串表示,即。 convo=

Fred
hello

John
hi

Bob
how is it going?

Jake
we are doing fine

如何反汇编和重新组装该字符串,以便将其拆分为 2 个字符串,其中 1 个字符串来自 Team_A 所说的内容,1 个字符串来自 Team_A 所说的内容?

输出:team_A_said="你好,怎么样?"team_B_said="嗨,我们做得很好"

线条并不重要。

我有这个可怕的find...然后slice代码,它是不可扩展的。有人可以建议其他东西吗?有图书馆可以帮助解决这个问题吗?

我在nltk库中没有找到任何内容

最佳答案

此代码假设 convo 的内容严格符合
他们说的名字\n内容\n\n
图案。它使用的唯一棘手的代码是 zip(*[iter(lines)]*3),它从 lines 列表创建一个字符串三元组列表。有关此技术和替代技术的讨论,请参阅 How do you split a list into evenly sized chunks in Python? .

#!/usr/bin/env python

team_ids = ('A', 'B')

team_names = (
('Fred', 'Bob'),
('John', 'Jake'),
)

#Build a dict to get team name from person name
teams = {}
for team_id, names in zip(team_ids, team_names):
for name in names:
teams[name] = team_id


#Each block in convo MUST consist of <name>\n<one line of text>\n\n
#Do NOT omit the final blank line at the end
convo = '''Fred
hello

John
hi

Bob
how is it going?

Jake
we are doing fine

'''

lines = convo.splitlines()

#Group lines into <name><text><empty> chunks
#and append the text into the appropriate list in `said`
said = {'A': [], 'B': []}
for name, text, _ in zip(*[iter(lines)]*3):
team_id = teams[name]
said[team_id].append(text)

for team_id in team_ids:
print 'Team %s said: %r' % (team_id, ' '.join(said[team_id]))

输出

Team A said: 'hello how is it going?'
Team B said: 'hi we are doing fine'

关于python - 基于列表反汇编和重新组装字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com