gpt4 book ai didi

python - 如何在Python中将多个字符变成一个字符?

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

我有以下句子:

sentence_1 = "online auto body" 

我在它的开头和结尾添加了以下字符 <s>指示它的开始和结束,因此我的句子现在如下:

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

我想把 sentence_1 中的单词做成三元组。如下:

('<s>','o','n')
('o', 'n', 'l')
('n', 'l', 'i')
('l', 'i', 'n')
('i', 'n', 'e')
('a', 'u', 't')
('u', 't', 'o')
('b', 'o', 'd')
('o', 'd', 'y')
('d', 'y', '<s>)

我尝试这样做的是以下代码:

from nltk import ngrams
n = 3
word_3grams = ngrams(sentence.split(), n)


for w_grams in word_3grams:
w_gram = list(w_grams)
print(w_grams[0])
for i in range(0,n):
letter_3grams = ngrams(w_grams[i],3)
for l_gram in letter_3grams:
print(l_gram)

但我得到的是:

('<', 's', '>')
('o', 'n', 'l')
('n', 'l', 'i')
('l', 'i', 'n')
('i', 'n', 'e')
('a', 'u', 't')
('u', 't', 'o')

等等。

问题是如何避免 <s> 被分割成 3 克并将其视为一个整体?

最佳答案

所需的输出显示输入字符串中的空格已被删除,因此不要忘记在拆分之前用空字符串替换空格:

sentence_1 = "online auto body"

lst = ['<s>'] + list(sentence_1.replace(' ','')) + ['<s>']
tri = [tuple(lst[n:n+3]) for n in range(len(lst)-2)]
print(tri)

此代码创建一个三元组列表,您可以进一步处理:

[('<s>', 'o', 'n'), ('o', 'n', 'l'), ('n', 'l', 'i'), ('l', 'i', 'n'), ('i', 'n', 'e'), ('n', 'e', 'a'), ('e', 'a', 'u'), ('a', 'u', 't'), ('u', 't', 'o'), ('t', 'o', 'b'), ('o', 'b', 'o'), ('b', 'o', 'd'), ('o', 'd', 'y'), ('d', 'y', '<s>')]

如果您只想打印三元组,请将最后两行替换为:

print('\n'.join(str(tuple(lst[n:n+3])) for n in range(len(lst)-2)))

输出:

('<s>', 'o', 'n')
('o', 'n', 'l')
('n', 'l', 'i')
('l', 'i', 'n')
('i', 'n', 'e')
('n', 'e', 'a')
('e', 'a', 'u')
('a', 'u', 't')
('u', 't', 'o')
('t', 'o', 'b')
('o', 'b', 'o')
('b', 'o', 'd')
('o', 'd', 'y')
('d', 'y', '<s>')

关于python - 如何在Python中将多个字符变成一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49975644/

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