gpt4 book ai didi

python - 如何以正确的顺序将句子中的单词插入到列表中

转载 作者:行者123 更新时间:2023-12-01 07:04:03 24 4
gpt4 key购买 nike

我有一个字符串/句子:

text = 'Obama and Putin had a meeting today in Russia over lunch where they discussed the new green deal and the Paris agreement.'

我有两个列表:

sentence_list = []
grouped_words = ['Obama and Putin', 'a meeting', 'today', 'Russia', 'lunch', 'the new green deal', 'the Paris agreement']

如何将 grouped_words 中的单词附加到 sentence_list,然后附加原始字符串 text 中不等于的单词grouped_words 中的单词到 sentence_list 中?最终列表如下所示:

['Obama and Putin', 'had', 'a meeting', 'today', 'in','Russia', 'over', 'lunch','where', 'they','discussed', 'the','new green deal', 'and', 'the Paris agreement']

此列表将 grouped_words 的内容保持与原始字符串相同的顺序,同时添加字符串中的新单词,也按相同的顺序。

我怎样才能得到一个像这样的列表?

感谢您的帮助!

最佳答案

想不出一个花哨的单行代码,所以这里有一个简单的循环方式:

text = 'Obama and Putin had a meeting today in Russia over lunch where they discussed the new green deal and the Paris agreement.'
sentence_list = []
grouped_words = ['Obama and Putin', 'a meeting', 'today', 'Russia', 'lunch', 'the new green deal', 'the Paris agreement']

for i in grouped_words:
while True:
if text.startswith(i):
text = text.replace(i+" ","")
sentence_list.append(i)
break
else:
new = text.split()[0]
sentence_list.append(new)
text = text.replace(new+" ","")

print (sentence_list)

#['Obama and Putin', 'had', 'a meeting', 'today', 'in', 'Russia', 'over', 'lunch', 'where', 'they', 'discussed', 'the new green deal', 'and', 'the Paris agreement']

关于python - 如何以正确的顺序将句子中的单词插入到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58514499/

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