gpt4 book ai didi

python - 在python中用多个匹配项划分字符串

转载 作者:行者123 更新时间:2023-12-02 19:10:26 25 4
gpt4 key购买 nike

我有一个字符串,必须为“words”中出现的单词拆分

words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement3 " # a single lined string

我正在使用的代码,有什么简单的方法吗?

  for l in words:
if l == "word1": t1 = text.split(l)
if l == "word2": t2 = str(t1[1]).split(l)
if l == "word3": t3 = str(t2[1]).split(l)

print(t1[0])
print(t2[0])
print(t3[0])

输出如下:

statement
statement1
statement2
statement3

最佳答案

如何使用 itertools.groupby :

from itertools import groupby

words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement "
delimiters = set(words)
statements = [
' '.join(g) for k, g in groupby(text.split(), lambda w: w in delimiters)
if not k
]
print(statements)

输出:

['long statement', 'statement1', 'statement2', 'statement3']

关于python - 在python中用多个匹配项划分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64377259/

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