【问题标题】:Create new tokens and tuples from existing ones based on conditions根据条件从现有令牌和元组创建新令牌和元组
【发布时间】:2016-12-19 11:13:34
【问题描述】:

这与 previous question 非常相关,但我很难适应我的用例。

我有一句话:"Forbes Asia 200 Best Under 500 Billion 2011"

我有类似的标记:

oldTokens = [u'Forbes', u'Asia', u'200', u'Best', u'Under', u'500', u'Billion', u'2011']

以及前一个解析器已经确定应该在哪里有位置或编号槽的索引:

numberTokenIDs =  {(7,): 2011.0, (2,): 200.0, (5,6): 500000000000.00}
locationTokenIDs = {(0, 1): u'Forbes Asia'}

token ID对应有位置或编号的token的索引,目的是获得一组新的token,如:

newTokens = [u'ForbesAsia', u'200', u'Best', u'Under', u'500Billion', u'2011']

使用新的数字和位置 tokenID 可能像(以避免索引越界异常):

numberTokenIDs =  {(5,): 2011.0, (1,): 200.0, (4,): 500000000000.00}
locationTokenIDs = {(0,): u'Forbes Asia'}

基本上我想通过新的减少标记集,并最终能够创建一个新句子,称为:

"LOCATION_SLOT NUMBER_SLOT Best Under NUMBER_SLOT NUMBER_SLOT"

通过检查新的令牌集并将正确的令牌ID 替换为LOCATION_SLOTNUMBER_SLOT。如果我使用当前的一组数字和位置令牌 ID 执行此操作,我会得到:

"LOCATION_SLOT LOCATION_SLOT NUMBER_SLOT Best Under NUMBER_SLOT NUMBER_SLOT NUMBER_SLOT".

我该怎么做?

另一个例子是:

Location token IDs are:  (0, 1)
Number token IDs are:  (3, 4)

旧样本令牌[u'United', u'Kingdom', u'USD', u'1.240', u'billion']

我想同时删除令牌并更改位置和数字令牌 ID 以便能够替换以下句子:

sampleTokens[numberTokenID] = "NUMBER_SLOT"
sampleTokens[locationTokenID] = "LOCATION_SLOT"

这样替换的令牌是[u'LOCATION_SLOT', u'USD', u'NUMBER_SLOT']

注意,如果元组中的值超过一个,则连接应该连接元组中的所有值(元组也可以包含>2个元素,例如The United States of America)。

【问题讨论】:

    标签: python loops tuples token tokenize


    【解决方案1】:

    这应该有效(如果我理解正确的话):

    token_by_index = dict(enumerate(oldTokens))
    groups = numberTokenIDs.keys() + locationTokenIDs.keys()
    for group in groups:
        token_by_index[group[0]] = ''.join(token_by_index.pop(index)
                                           for index in group)
    newTokens = [token for _, token in sorted(token_by_index.items(),
                                              key=lambda (index, _): index)]
    

    查找新的令牌 ID:

    new_index_by_token = dict(map(lambda (i, t): (t, i), enumerate(newTokens))
    numberTokenIDs = {(new_index_by_token[token_by_index[group[0]]],): value
                      for group, value in numberTokenIDs.items()}
    locationTokenIDs = {(new_index_by_token[token_by_index[group[0]]],): value
                        for group, value in locationTokenIDs.items()}
    

    【讨论】:

    • 如何返回新的数字和位置 tokenID 以匹配这些新令牌?例如numberTokenIDs = {(5,): 2011.0, (1,): 200.0, (4,): 500000000000.00}
    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2020-05-01
    • 2017-11-20
    • 1970-01-01
    • 2020-11-09
    • 2022-11-17
    相关资源
    最近更新 更多