简体   繁体   中英

Python: Why can't my program write to a file from a list?

I have a txt file of clues eg A is #, B is ?, C is @ etc.

I'm trying to read a ciphertxt file and swap the cipher-symbol using my txt file of clues above which I have imported into a list.

For some reason, it won't perform my substitution as expected.

def Import_Clues_to_Lists():
global letter_list
global symbol_list
file_clues=open('clues.txt','r')
for line in file_clues:
    for character in line:
        if character.isalpha() == True:
            letter_list[int(ord(character)-65)]  = line[0]
            symbol_list[int(ord(character)-65)] = line[1]
file_clues.close()


def Perform_Substitution():
Import_Clues_to_Lists()
print(letter_list)
print(symbol_list)
file_words = open('words.txt','r')
temp_words = open('wordsTEMP.txt','w')
for line in file_words:
    for character in line:
        if character.isalpha() == False:
            position = symbol_list.index(character) # get the position for the list
            equivalent_letter = letter_list[position] # get the equivalent letter
            temp_words.write(equivalent_letter) # substitute the symbol for the letter in the temp words file.
        else:
            temp_words.write(character)
file_words.close()
temp_words.close()
import os # for renaming files
#os.remove('words.txt')
#os.rename('wordsTEMP.txt','words.txt')
menu()

Any ideas where my logic has gone wrong?

It might be better if you use a dictionary to hold your symbols and the characters they represent - a substitution dictionary. It will make your code more readable which might make it easier to find the problem.

If clues.txt looks something like this:

a!
b#
c$
d%

Try these out:

def Import_Clues_to_Lists():
    '''Create a substitution dictionary

    returns dict, {symbol : character}
    '''
    sub = dict()
    with open('clues.txt','r') as file_clues:
        for line in file_clues:
            # symbol = line[1], letter = line[0]
            sub[line[1]] = line[0]
    return sub

def Perform_Substitution():
    '''Iterate over characters of a file and substitute letters for symbols.

    creates a new file --> wordsTEMP.txt

    returns None
    '''
    # substitute is a dictionary of {symbol : character} pairs
    substitute = Import_Clues_to_Lists()
    for sym, char in substitute.items(): print(sym, char)
    with open('words.txt','r') as file_words, open('wordsTEMP.txt','w') as temp_words:
        for line in file_words:
            for character in line:
                if character in substitute:
                    character = substitute[character]
                temp_words.write(character)

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