我是python新手,遇到了一个问题。我要做的是,我有一个字符串,其中包含两个人之间的对话:
str = " dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
我想用dylankid和senpai作为名称从字符串中创建2个列表:
^{pr2}$这是我正在挣扎的地方,在列表dylankid中,我想把所有在'dylankid'后面,但在下一个'dylankid'或'senpai'之前的单词放在字符串中 senpai列表也是如此 看起来像这样
dylankid = ["random words", "random words", "random words"]
senpai = ["random words", "random words", "random words"]
dylankid包含来自dylankid的所有消息,反之亦然。在
我已经研究过将其切片并使用split()
和re.compile()
,但我无法找到一种方法来指定开始切片和停止位置。在
希望它足够清楚,任何帮助将不胜感激:)
这可以收紧,但应该很容易扩展到更多的用户名。在
结果是:
^{pr2}$以下代码将创建一个dict,其中keys是person,value是消息列表:
它将产生以下输出:
^{pr2}$您可以使用groupby,拆分单词并使用
__contains__
进行分组输出:
^{pr2}$下一次我们用一个单词的名字来连接。在
如果名称后碰巧没有单词,则可以使用空列表作为下一次调用的默认值:
一些较大字符串的计时:
两者都重新生成相同的输出:
相关问题 更多 >
编程相关推荐