好吧,所以我一直在为DAYS努力解决这个问题而苦苦挣扎。我被指派制作一个类似于" cipher.py"的代码。导入加密文本文件,使用" key.txt"解密,然后将解密的信息写入" decrypted.txt"
我一直得到encryptedWords = encryptedWords.replace(str(encryptedFiles [i] [1]),str(decryptedFiles [i] [0])) AttributeError:' list'对象没有属性'替换'
有什么想法吗?
key = open("key.txt", "r")
encrypted = open("encrypted.txt","r" )
decrypted = open("decrypted.txt", "w")
encryptedFiles = []
decryptedFiles = []
unencrypt= ""
for line in key:
linesForKey = line.split()
currentEncrypted = (line[0])
currentDecrypted = (line[1])
encryptedFiles.append(currentEncrypted)
decryptedFiles.append(currentDecrypted)
key.close()
##########################################
encryptedWords = []
encryptedString = ""
lines = encrypted.readlines()
for line in lines:
letter = list(line)
encryptedWords += letter
for i in range(len(encryptedWords)):
encryptedWords = encryptedWords.replace(str(encryptedFiles[i][1]),str(decryptedFiles[i][0]))
encrypted.close()
decrypted.write(encryptedWords)
decrypted.close()
答案 0 :(得分:0)
The .replace()
attribute is only for strings。我认为你是+=
,你可以将encryptedWords
添加为字符串。
+=
有趣地与列表一起工作:
>>> array = []
>>> string = ''
>>> string+='hello'
>>> array+='hello'
>>> string
'hello'
>>> array
['h', 'e', 'l', 'l', 'o']
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>>
+=
接受字符串,并且分组必须像list(string)
那样。您可以将encryptedWords
更改为字符串(encryptedWords = ''
),也可以使用''.join(encryptedWords)
或' '.join(encryptedWords)
转换回字符串,而不是这样:< / p>
>>> array = list('hello')
>>> array
['h', 'e', 'l', 'l', 'o']
>>> ''.join(array)
'hello'
>>> ' '.join(array)
'h e l l o'
>>>