gpt4 book ai didi

python - 如何向元组或列表中的字符串元素添加字符?

转载 作者:行者123 更新时间:2023-12-01 09:31:25 25 4
gpt4 key购买 nike

我有以下句子:

sentence = "<s> online auto body <s>" 

我想首先将其变成 3-gram 的单词:

('<s>', 'outline', 'auto')
('online', 'auto', 'body')
('auto', 'body', '<s>')

为此,我使用了以下代码:

sentence = '<s> online auto body <s>'
n = 3
word_3grams = ngrams(sentence.split(), n)
for grams in word_3grams:
print(grams)

现在,我想在每个单词的开头和结尾处添加“#”,如下所示:

('#<s>#','#outline#','#auto#')
('#online#', '#auto#', '#body#')
('#auto#', '#body#', '#<s>#')

但我不知道该怎么做才能得到它。作为旁注,这里的元素是元组,但它不介意使用列表。

最佳答案

您想要一个类似滑动窗口的功能。

from itertools import islice

sentence = "<s> online auto body <s>"
myList = sentence.split()
myList = ['#' + word + '#' for word in myList]

slidingWindow = [islice(myList, s, None) for s in range(3)]
print(list(zip(*slidingWindow)))

# [('#<s>#', '#online#', '#auto#'), ('#online#', '#auto#', '#body#'), ('#auto#', '#body#', '#<s>#')]

关于python - 如何向元组或列表中的字符串元素添加字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941816/

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