gpt4 book ai didi

python - 查找已连接的 token

转载 作者:行者123 更新时间:2023-11-28 16:29:00 25 4
gpt4 key购买 nike

我编写了获取文本标记作为输入的代码:

tokens = ["Tap-", "Berlin", "Was-ISt", "das", "-ist", "cool", "oh", "Man", "-Hum", "-Zuh-UH-", "glit"]

代码应该找到所有包含连字符或用连字符相互连接的标记:基本上输出应该是:

[["Tap-", "Berlin"], ["Was-ISt"], ["das", "-ist"], ["Man", "-Hum", "-Zuh-UH-", "glit"]]

我写了一个代码,但不知何故我没有得到带有连字符的标记:试试看:http://goo.gl/iqov0q

def find_hyphens(self):
tokens_with_hypens =[]


for i in range(len(self.tokens)):

hyp_leng = 0

while self.hypen_between_two_tokens(i + hyp_leng):
hyp_leng += 1

if self.has_hypen_in_middle(i) or hyp_leng > 0:
if hyp_leng == 0:
tokens_with_hypens.append(self.tokens[i:i + 1])
else:
tokens_with_hypens.append(self.tokens[i:i + hyp_leng])
i += hyp_leng - 1

return tokens_with_hypens

我做错了什么?有没有更高效的解决方案?谢谢

最佳答案

我在您的代码中发现了 3 个错误:

1) 您在这里比较的是 tok1 的最后两个字符,而不是 tok1 的最后一个字符和 tok2 的第一个字符:

if "-" in joined[len(tok1) - 2: len(tok1)]:
# instead, do this:
if "-" in joined[len(tok1) - 1: len(tok1) + 1]:

2) 您在这里省略了最后一个匹配的标记。将此处切片的结束索引增加 1:

tokens_with_hypens.append(self.tokens[i:i + hyp_leng])
# instead, do this:
tokens_with_hypens.append(self.tokens[i:i + 1 + hyp_leng])

3) 您不能在 python 中操作 for i in range 循环的索引。下一次迭代将只检索下一个索引,覆盖您的更改。相反,您可以像这样使用 while 循环:

i = 0
while i < len(self.tokens):
[...]
i += 1

这 3 次更正导致您的测试通过:http://goo.gl/fd07oL


尽管如此,我还是忍不住从头开始编写算法,尽可能简单地解决您的问题:

def get_hyphen_groups(tokens):
i_start, i_end = 0, 1
while i_start < len(tokens):
while (i_end < len(tokens) and
(tokens[i_end].startswith("-") ^ tokens[i_end - 1].endswith("-"))):
i_end += 1
yield tokens[i_start:i_end]
i_start, i_end = i_end, i_end + 1


tokens = ["Tap-", "Berlin", "Was-ISt", "das", "-ist", "cool", "oh", "Man", "-Hum", "-Zuh-UH-", "glit"]

for group in get_hyphen_groups(tokens):
print ("".join(group))

要排除 1 元素组,就像在您的预期结果中一样,将 yield 包装到此 if 中:

if i_end - i_start > 1:
yield tokens[i_start:i_end]

要包含已包含连字符的 1 元素组,请将 if 更改为例如:

if i_end - i_start > 1 or "-" in tokens[i_start]:
yield tokens[i_start:i_end]

关于python - 查找已连接的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987472/

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