首页 > 解决方案 > 替换与键匹配的单词在 Python 中不起作用

问题描述

所以我试图用它的值替换与字典中任何键匹配的单词。

以下是我拥有的当前代码,我的代码没有替换任何东西。

       for k, v in fdict.items():
           if word == k:
               word == v

所以基本上最后我希望发生以下情况。

标签: python

解决方案


你可以简单地做

for word in (jsondata['value']['segments'][i]['transcriptionData']['content']).split():
    word = fdict.get(word, word)

通过使用get,您可以看到是否word是有效键,如果是,则返回关联的值,否则,将第二个参数作为默认值返回,在这种情况下为word。您不需要遍历fdict,因为这首先违背了字典的目的。成员资格测试是一个持续时间且快速的过程。

如果您希望这反映在字典本身中,则需要重新分配该键的值:

# changing this to be more pythonic and readable
for segment in jsondata['value']['segments']:
    # assigning this to be a different variable for readability
    words = segment['transcriptionData']['content'].split()
    # join will make this a string again so we can re-assign it
    # to the key
    words = ' '.join(fdict.get(word, word) for word in words)

    # Now this will be reflected in your json
    segment['transcriptionData']['content'] = words

此外,在您的if声明中,word==v将返回False,作为==相等性测试,而不是赋值,应该是word = v

要解决问题中的更新,您永远不会在words任何地方编写更新。程序中的数据不是文件,因此在将数据写回文件之前,对数据所做的任何修改都不会反映在文件中。

# after you update words
# Note, this is a different file path, as w will truncate (wipe out) the 
# file if it exists, so use a different file path until you are sure your
# logic is sound
with open('somefile.json', 'w') as fh:
    json.dump(jsondata)

推荐阅读