简体   繁体   中英

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. 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. 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"] .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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