Reputation: 11
key_file = open("key.txt", "r")
key = key_file.read().split(',')
text_file = open("plaintext.txt", "r")
text = text_file.read().split(' ')
key = map(int, key)
for i in range(len(key));
print text[i]
text_file.close()
key_file.close()
I am new to Python but I know very basic C programming. I am trying to print the list 'text' (list of char's) in order of the integers in the list 'key', or essentially use key[ ] integers to dictate the index of text[ ] to print. I may be going about this in the complete wrong way but this is what I have so far. It's printing the text list in it's original order, not in the order of key[ ].
key_file.txt is a random assortment of integers ranging from 1-26. text_file.txt is 26 characters, in this case it's a through z. the output should essentially be the alphabet rearranged according to key_file.txt.
Upvotes: 0
Views: 818
Reputation: 18093
This should work for you. I'm assuming the keys are zero indexed. Your mileage may vary depending on the actual structure of the files.
with open("key.txt", "r") as key_list:
with open("plaintext.txt", "r") as text_list:
for key in key_list:
try:
print text_list[key]
except IndexError:
print "Invalid Key"
Upvotes: 0
Reputation: 361595
Since you want to print different characters, don't split text
up into words. Leave it as a single string.
text = text_file.read()
Then loop over the entries in key
. Since the numbers in key.txt
are 1-26, you'll need to subtract 1 to turn that into 0-25.
for i in key:
print text[i - 1]
Upvotes: 1
Reputation: 4801
Assuming that key is a list of integers (1-26) in random order, and text is a list of 26 characters:
key_file = open("key.txt", "r")
key = key_file.read().split(',')
text_file = open("plaintext.txt", "r")
text = text_file.read().split(' ')
key = map(int, key)
for i in key:
print text[i - 1]
text_file.close()
key_file.close()
Upvotes: 1