Python 读取文本文件并将其替换为字典中的值
我有一本python词典。我还有一个文本文件,其中每一行都是不同的单词。我想对照字典的键检查文本文件的每一行,如果文本文件中的行与键匹配,我想将该键的值写入输出文件。有没有一个简单的方法可以做到这一点。这可能吗 例如,我正在这样读取我的文件:Python 读取文本文件并将其替换为字典中的值,python,dictionary,Python,Dictionary,我有一本python词典。我还有一个文本文件,其中每一行都是不同的单词。我想对照字典的键检查文本文件的每一行,如果文本文件中的行与键匹配,我想将该键的值写入输出文件。有没有一个简单的方法可以做到这一点。这可能吗 例如,我正在这样读取我的文件: test = open("~/Documents/testfile.txt").read() dic = {"a": ["ah0", "ey1"], "a's&qu
test = open("~/Documents/testfile.txt").read()
dic = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
标记它,对于每个单词标记,我想查找字典,我的字典设置如下:
test = open("~/Documents/testfile.txt").read()
dic = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
如果我在文件中遇到字母'a'
,我希望它输出[“ah0”,“ey1”]
您可以尝试:
for line in all_lines:
for val in dic:
if line.count(val) > 0:
print(dic[val])
这将检查文件中的所有行,如果该行包含来自dic的字母,则它将在字典中打印与该字母相关的项目(您必须执行类似于
all_lines=test.readlines()
的操作才能获得列表中的所有行)dic[val]
将列表分配给值[“ah0”、“ey1”]
因此,您不仅需要打印它,还可以在其他地方使用它您可以尝试一下:
#dictionary to match keys againts words in text filee
dict = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
# Read from text filee
open_file = open('sampletext.txt', 'r')
lines = open_file.readlines()
open_file.close()
#search the word extracted from textfile, if found in dictionary then print list into the file
for word in lines:
if word in dict:
write_to_file = open('outputfile.txt', 'w')
write_to_file.writelines(str(dict[word]))
write_to_file.close()
注意:如果从中读取的文本文件有多行,则可能需要删除换行符“\n”