首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据两个单词在列表中拆分句子?

如何根据两个单词在列表中拆分句子?
EN

Stack Overflow用户
提问于 2022-01-11 19:56:56
回答 3查看 78关注 0票数 0

我有一个类似于这个lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']的字符串列表,如果它们有或作为分隔符,我想将列表中的单词分开,这样最终的结果就是['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']。我怎样才能做到这一点?我的努力是:

代码语言:javascript
复制
to_ret = []
for words in lst:
 splitted = words.split(' and')
 to_ret.extend(splitted)
new_ret = []
for words in to_ret:
 splitted = words.split(' with')
 new_ret.extend(splitted)

但这看起来很重复。对清洁代码有什么建议吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-01-11 20:02:52

您可以使用正则表达式来处理多个分隔符,并使用链表将所有子列表放在一起。

代码语言:javascript
复制
import re
from itertools import chain
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']

output = [w.strip() for w in chain.from_iterable([re.split(r'and|with',x) for x in lst])]
print(output)

输出

代码语言:javascript
复制
['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']
票数 3
EN

Stack Overflow用户

发布于 2022-01-11 20:03:50

代码语言:javascript
复制
#my interpretation would be
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']


toSplitWith= ["and" , "with"]

ans=[]
for word in lst:
    for sprt in toSplitWith:
        if sprt in word:
            ans.extend(word.split(sprt))

print(ans)
票数 0
EN

Stack Overflow用户

发布于 2022-01-11 20:06:53

如果你喜欢,你可以这样做:-

代码语言:javascript
复制
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
to_ret = []
for i,word in enumerate(lst):
 splittedand = word.split(' and')
 splittedwith = word.split(' with')
 to_ret.extend(splittedand)
 to_ret.extend(splittedwith)
 to_ret.remove(word)
print(to_ret)

退出:

代码语言:javascript
复制
['John Kim', ' Kerry Lin', 'John Cena', 'Kim Rai', ' Kaster Baldwin']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70672708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档