python - 替换与键匹配的单词在 Python 中不起作用
问题描述
所以我试图用它的值替换与字典中任何键匹配的单词。
以下是我拥有的当前代码,我的代码没有替换任何东西。
for k, v in fdict.items():
if word == k:
word == v
所以基本上最后我希望发生以下情况。
解决方案
你可以简单地做
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)
推荐阅读
- asp.net - 有没有办法可以从 ASP.NET Core 项目中删除数据库迁移?
- python - 将任意字符串转换为可读的掷骰结果的最佳方法是什么?
- java - Android Studio:json数组中只显示一张图片
- tabs - 如何在 doxygen 文档中添加我们自己定义的选项卡
- android - 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障 - 带有 Glide 的 Firebase UI
- javascript - 无法将数据从 JSON 加载到数据表中
- reactjs - 单击项目覆盖另一个数据
- android - Android:当我使用 android:configChanges="orientation|keyboardHidden"> 时,横向模式的视图会发生变化
- .net - 无法加载文件或程序集“System.Drawing,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a”或其依赖项之一
- python - 有没有办法指定一个程序在另一个 for 循环中迭代整个 for 循环后执行一个函数?