将 .txt 文件转换为 Python 中字符的 table 3
Converting .txt file into a table of characters in Python 3
这里有点问题:
正在尝试创建我自己的 "Aplhabet",我想将其应用于我的 .txt、.doc、.odt 文档以对其进行加密。
我想问一下,如何将.txt、.doc、.odt文件转换成一个字符列表,这样我就可以一个一个地更改为我自己的"Alphabets"个字符。
然后再转换回来保存。
我尝试使用:
c = ('test.txt')
with open(c, 'w', encoding='utf-8') as a_file:
#Here I was trying writing the entry right into the code to be written into the file
a_file.write('Neco jineho napsaneho')
for i, v in enumerate(c):
c[i] = v.replace("N", "3")
with open(c, encoding='utf-8') as a_file:
print(a_file.read())
但是由于 "c" 是一个 .txt 文件而不是一个列表,它无法正常工作,只是给我这个错误:
c[i] = v.replace("N", "5")
TypeError: 'str' object does not support item assignment
如有任何帮助,我们将不胜感激!
干杯,
J
首先,这样做
with open(c, 'w', encoding='utf-8') as a_file:
立即销毁您的文件内容。在写回之前你必须完整地阅读它
其次,for i, v in enumerate(c):
正在迭代 文件名 。不能工作! (这解释了你得到的错误:你试图加密文件名就地:字符串是不可变)。反正不是你想做的...
而且您不需要 enumerate
。只需在迭代文件(文件行)时使用 listcomp 创建一个列表
with open(c, 'r', encoding='utf-8') as a_file:
lines = [v.replace("N", "3") for v in a_file]
# now write the "encrypted" file back using the same name
with open(c, 'w', encoding='utf-8') as a_file:
a_file.write('Neco jineho napsaneho')
a_file.writelines(lines)
注意:如果您想要更复杂的加密,请将 v.replace("N", "3")
替换为自定义 encrypt(v)
。
lines = [encrypt(v) for v in a_file]
与 encrypt
定义为:
def encrypt(v):
return v.replace("N","3").replace("Z","5")
(效率不是很高,只是举个例子,有字典就更好了)
这里有点问题:
正在尝试创建我自己的 "Aplhabet",我想将其应用于我的 .txt、.doc、.odt 文档以对其进行加密。
我想问一下,如何将.txt、.doc、.odt文件转换成一个字符列表,这样我就可以一个一个地更改为我自己的"Alphabets"个字符。 然后再转换回来保存。
我尝试使用:
c = ('test.txt')
with open(c, 'w', encoding='utf-8') as a_file:
#Here I was trying writing the entry right into the code to be written into the file
a_file.write('Neco jineho napsaneho')
for i, v in enumerate(c):
c[i] = v.replace("N", "3")
with open(c, encoding='utf-8') as a_file:
print(a_file.read())
但是由于 "c" 是一个 .txt 文件而不是一个列表,它无法正常工作,只是给我这个错误:
c[i] = v.replace("N", "5")
TypeError: 'str' object does not support item assignment
如有任何帮助,我们将不胜感激!
干杯,
J
首先,这样做
with open(c, 'w', encoding='utf-8') as a_file:
立即销毁您的文件内容。在写回之前你必须完整地阅读它
其次,for i, v in enumerate(c):
正在迭代 文件名 。不能工作! (这解释了你得到的错误:你试图加密文件名就地:字符串是不可变)。反正不是你想做的...
而且您不需要 enumerate
。只需在迭代文件(文件行)时使用 listcomp 创建一个列表
with open(c, 'r', encoding='utf-8') as a_file:
lines = [v.replace("N", "3") for v in a_file]
# now write the "encrypted" file back using the same name
with open(c, 'w', encoding='utf-8') as a_file:
a_file.write('Neco jineho napsaneho')
a_file.writelines(lines)
注意:如果您想要更复杂的加密,请将 v.replace("N", "3")
替换为自定义 encrypt(v)
。
lines = [encrypt(v) for v in a_file]
与 encrypt
定义为:
def encrypt(v):
return v.replace("N","3").replace("Z","5")
(效率不是很高,只是举个例子,有字典就更好了)