【问题标题】:Deleting previous token in a sentence if same as current token python如果与当前标记python相同,则删除句子中的前一个标记
【发布时间】:2016-07-21 14:23:04
【问题描述】:

我有 2 个键值对字典,例如:

tokenIDs2number = {(6, 7): 1000000000.0, (22,): 700.0, (12,): 3000.0}

tokenIDs2number = {(27, 28): u'South Asia'}

key 是句子中 number 和 location slots 的索引位置的元组:

GDP in 2007 totaled about $ 1 billion , or about $ 3,000 per capita -LRB- exceeding the average of about $ 700 in the rest of South Asia -RRB- .

我想遍历数字和位置的所有元组,如果它们彼此相邻,则从元组中删除值,例如制作它们:

tokenIDs2number = {(7,): 1000000000.0, (22,): 700.0, (12,): 3000.0}

tokenIDs2number = {(28,): u'South Asia'}

这样以后,我可以用位置和数字槽填充这个句子标记,所以句子变成:

GDP in 2007 totaled about $ NUMBER_SLOT , or about $ NUMBER_SLOT per capita -LRB- exceeding the average of about $ NUMBER_SLOT in the rest of LOCATION_SLOT -RRB- .

代替:

GDP in 2007 totaled about $ NUMBER_SLOT NUMBER_SLOT , or about $ NUMBER_SLOT per capita -LRB- exceeding the average of about $ 700 in the rest of LOCATION_SLOT LOCATION_SLOT -RRB- .

当前代码:

for locationTokenIDs, location in tokenIDs2location.items():
  for numberTokenIDs, number in tokenIDs2number.items():
    prevNoID=numberTokenIDs[0]
    prevLocID=locationTokenIDs[0]
    for numberTokenID in numberTokenIDs:
        for locationTokenID in locationTokenIDs:
            if numberTokenID==prevNoID+1:
                numberTokenIDs.remove(numberTokenIDs[prevNoID])
                if numberTokenID>0 and numberTokenID<(len(sampleTokens)-1):
                    prevNoID = numberTokenID
            if locationTokenID==prevLocID+1:
                locationTokenIDs.remove(locationTokenIDs[prevLocID])
                if locationTokenID>0 and locationTokenID<(len(sampleTokens)-1):
                    prevLocID = locationTokenID

但是,我似乎不能只从元组中删除数字,所以我正在努力弄清楚如何做到这一点。

【问题讨论】:

  • 元组是不可变的,你试过用列表吗?
  • @Yegers 不能使用列表作为键。它们是可变的,因此不能有意义地散列,因此实际上不是可散列的。 dicts 使用哈希来存储东西。

标签: python dictionary tuples


【解决方案1】:

由于tuples(通常是dict 键)是不可变的,因此您不能直接更改键。但是,您可以使用字典理解将您的 dict 转换为您需要的内容:

tokenIDs2number = {(6, 7): 1000000000.0, (22,): 700.0, (12,): 3000.0}
tokenIDs2number = {(k[-1],): v for k, v in tokenIDs2number.items()}

使用k[-1] 始终访问最后一个元素可以让您以同样的方式处理任意长度的元组。

【讨论】:

  • 出于兴趣,我该如何改变,所以我总是抓住一组连续元组中的第一个元素,例如tokenIDs2number = tokenIDs2number = {(27,): u'South Asia'}
  • 使用索引[0] 而不是[-1]。我建议您详细了解 list 和 dict 理解,以了解我提供的代码的作用。从长远来看,它将为您节省大量时间。
猜你喜欢
  • 2017-02-10
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 2016-01-17
  • 1970-01-01
相关资源
最近更新 更多