dict_1 = {"a":5 ,"b":8 ,"c":12}
dict_2 = {"a":10 ,"b":14 ,"c":20}
dict_3 = {"a":15 ,"b":20 ,"c":28}
1.now i have three different words in a txt file example in order
abc
cba
bca
I want the result of the addition to be written with the values corresponding to the letters in the dictionary I showed above.
so the result is first word "abc" = 47 (5 14 28)
second word "cba" = 41 (12 14 15)
third word "bca"= 43 (8 20 15)
using the first dictionary for the first letter of the word, the second dictionary for the second letter, and the third dictionary for the third letter. how can i do this using python
CodePudding user response:
Here's one way to do it. In the same working directory as the notebook, I've created a text file data.txt
which looks like this:
abc
cba
bca
ab
a
abcd
Here is where to store the file data.txt
import os
file_path = os.getcwd()
print(file_path) #this is where to store the file "data.txt"
After that, I've created a reference dictionary ref_dict
:
ref_dict = {
0: {'a': 5, 'b': 8, 'c': 12, 'd': 4},
1: {'a': 10, 'b': 14, 'c': 20, 'd': 4},
2: {'a': 15, 'b': 20, 'c': 28, 'd': 4},
3: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
}
with open('data.txt') as f:
words = f.readlines()
for word in words:
total = 0
for i, letter in enumerate(word.strip()):
total = ref_dict[i][letter]
print(word.strip(), total)
Output:
abc 47
cba 41
bca 43
ab 19
a 5
abcd 51