简体   繁体   English

读取文本文件并将其替换为字典中的值

[英]Reading a text file and replacing it to value in dictionary

I have a dictionary made in python. I also have a text file where each line is a different word.我有一本 python 制作的字典。我还有一个文本文件,其中每一行都是一个不同的词。 I want to check each line of the text file against the keys of the dictionary and if the line in the text file matches the key I want to write that key's value to an output file.我想根据字典的键检查文本文件的每一行,如果文本文件中的行与键匹配,我想将该键的值写入 output 文件。 Is there an easy way to do this.是否有捷径可寻。 Is this even possible?这可能吗?

for example I am reading my file in like this:例如,我正在这样阅读我的文件:

test = open("~/Documents/testfile.txt").read()

tokenising it and for each word token I want to look it up a dictionary, my dictionary is setup like this:对其进行标记化,对于我想查找字典的每个单词标记,我的字典设置如下:

dic = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}

If I come across the letter 'a' in my file, I want it to output ["ah0", "ey1"] .如果我在文件中遇到字母'a' ,我希望它为 output ["ah0", "ey1"]

you can try:你可以试试:

for line in all_lines:
    for val in dic:
        if line.count(val) > 0:
            print(dic[val])

this will look through all lines in the file and if the line contains a letter from dic, then it will print the items associated with that letter in the dictionary (you will have to do something like all_lines = test.readlines() to get all the lines in a list) the dic[val] gives the list assined to the value ["ah0", "ey1"] so you do not just have to print it but you can use it in other places这将查看文件中的所有行,如果该行包含来自 dic 的字母,那么它将在字典中打印与该字母关联的项目(您必须执行类似all_lines = test.readlines()的操作来获取所有列表中的行) dic[val]给出分配给值["ah0", "ey1"]的列表,因此您不仅需要打印它,还可以在其他地方使用它

you can give this a try:你可以试试这个:

#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()

Note: you may need to strip the newline "\n" if the textfile you read from have multiple lines注意:如果您读取的文本文件有多行,您可能需要去除换行符“\n”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM