Reputation: 61
I'm trying to create a program to do very simple encryption/compression.
Basically, the program requests input in the form of a sentence which is split into words, e.g.
this is the gamma
I then have two lists:
mylist1 = ("alpha","beta","gamma","delta")
mylist2 = ("1","2","3","4")
Each word is matched against a list which contains a number of words. if the words are present in the list then it should replace the word with the corresponding number in the other list. The output should be:
this is the 3
Here is the code I have so far:
text = input("type your sentence \n")
words = text.split(" ")
mylist1 = ("alpha","beta","gamma","delta")
mylist2 = ("1","2","3","4")
#I was looking at zipping the lists together but wasn't sure I was on the right track
#ziplist = zip(mylist1, mylist2)
for word in words:
if word in mylist1:
text = text.replace(word,mylist2[])
print (text)
This question that I was looking into yesterday shows how to do this using a dictionary but I encountered a problem when trying to convert the text file back from numbers to words again. (I swapped the Keys and Values around. I'm pretty certain I shouldn't do that)
Any input would be fantastic.
Upvotes: 0
Views: 554
Reputation: 58
You need to get the index of word from mylist1 and replace the occurrence of word in the variable text with the element at that same index in mylist2
text = text.replace(word, mylist2[mylist1.index(word)])
Upvotes: 2