我有一本python词典。我还有一个文本文件,其中每一行都是不同的单词。我想对照字典的键检查文本文件的每一行,如果文本文件中的行与键匹配,我想将该键的值写入输出文件。有没有一个简单的方法可以做到这一点。这可能吗
例如,我正在这样读取我的文件:
test = open("~/Documents/testfile.txt").read()
标记它,对于每个单词标记,我想查找字典,我的字典设置如下:
dic = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
如果我在文件中遇到字母'a'
,我希望它输出["ah0", "ey1"]
您可以尝试:
这将检查文件中的所有行,如果该行包含来自dic的字母,那么它将在字典中打印与该字母相关的项目(您必须执行类似
all_lines = test.readlines()
的操作才能获得列表中的所有行)dic[val]
将列表分配给值["ah0", "ey1"]
所以你不必只打印它,你还可以在其他地方使用它您可以尝试一下:
注意:如果从中读取的文本文件有多行,则可能需要删除换行符“\n”
相关问题 更多 >
编程相关推荐