【问题标题】:Replacing list item based on another list using pseudo-token使用伪令牌基于另一个列表替换列表项
【发布时间】:2020-02-24 15:38:01
【问题描述】:

所以,我是 Python 新手。如果我的列表的值也在另一个列表中,我想替换它们并将它们更改为指定的值,伪令牌(OOV)。我已经将它们变成了令牌,并使用正则表达式稍微清理了代码。 这是我的代码:

def replace_words(list1, list2):
  for word in list1:
    for words in list2:
     if word == words:
        word = "OOV"




replace_words(list1, list2)
list1.count("OOV") #this keeps showing 0, so something is wrong...

【问题讨论】:

  • 你的list1和list2是什么?
  • 如果有示例输入能够实际重现这一点,将会有很大帮助。

标签: python replace token


【解决方案1】:

您的代码不起作用,因为您试图为变量word 分配一个新值OOV,这很好,但实际上并没有更改list1 中的那个元素。所以你需要在list1

里面改变item inplace

试试这个:

def replace_words(list1, list2):
  for idx in range(len(list1)):
      if list1[idx] in list2:
          list1[idx] = "OOV"

当你现在执行>>>list1.count("OOV") 时,如果list1 中有值,它也不会返回0,而list2 中也有值

希望这会有所帮助!

【讨论】:

  • @KatGl 如果这回答了您的问题,您可以接受该答案作为正确答案以标记问题已完成。
【解决方案2】:

您做错了什么是假设设置word = "oov" 将替换列表中的元素。这不是真的,您需要通过访问该列表的索引来替换。阅读更多关于here

以下应该可以工作

def replace_words(list1, list2):
  for i in range(0,len(list1)-1):#using index
    for words in list2:
     if list1[i] == words:
        list1[i] = "OOV"

replace_words(list1, list2)
list1.count("OOV") 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 2011-03-29
    相关资源
    最近更新 更多