簡體   English   中英

Python:為什么我的程序無法從列表寫入文件?

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

我有一個線索的txt文件,例如A是#,B是?,C是@等。

我正在嘗試讀取一個ciphertxt文件,並使用線索txt文件替換該cipher-符號,上面已將其導入列表。

由於某些原因,它不會按預期執行我的替換。

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()

有什么想法我的邏輯錯了嗎?

如果使用字典來保存符號及其代表的字符,則可能會更好- 替代字典。 這將使您的代碼更具可讀性,這可能會更容易發現問題。

如果clues.txt看起來像這樣:

a!
b#
c$
d%

試試看:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM