python - 有没有更优雅的方法来重构这个非常线性的代码块?
问题描述
我为课堂作业制作了这个解决方案。它本质上是一个凯撒密码,它将文件作为输入,以及一个移位值,并输出“encrypted.txt”。这是非常基本的,不包括输入验证。
现在,它只是一系列逐项填充和转换的列表。
dir = input("What is your file titled?: ")
shift = int(input("Enter a shift number for document: "))
doc = open(dir, "r")
encrypted_doc = open("encrypted.txt","w")
#split document into list of characters
doc_list=[]
with doc as fileobj:
for line in fileobj:
for ch in line:
doc_list.append(ch)
doc.close()
ord_list = []
for char in doc_list:
ord_list.append(int(ord(char)))
cipher_ord_list = []
for ord in ord_list:
cipher_ord_list.append(ord + shift)
#convert cipher list back into characters, then string
cipher_list = []
for ord in cipher_ord_list:
cipher_list.append(chr(ord))
ciphered_string = "".join(cipher_list)
encrypted_doc.write(ciphered_string)
encrypted_doc.close()
我很好奇是否有办法减少必要的行数或者让它更漂亮?感觉很笨拙。
解决方案
你可以缩短这个:
- 使用
with open(...) as f: ...
语法并删除.close()
- 使用字典或使用 str.translate() 创建查找翻译表
- 并使用内置功能:
import string
import os
# Looks for the first .py file in the current dir and translates it:
for root,dirs,files in os.walk("./"):
filename = [f for f in files if f.endswith(".py")][0]
shift = 2222 # int(input("Enter a shift number for document: "))
shift_by = shift % len(string.printable) # so it works for shifts of 10000
mapper = str.maketrans( string.printable,
string.printable[shift_by:] + string.printable[:shift_by])
revmap = str.maketrans( string.printable[shift_by:] + string.printable[:shift_by],
string.printable )
# translate documents
doc_list=[]
with open(filename) as f:
ciphered_string = f.read().translate(mapper)
with open("encrypted.txt","w") as encrypted_doc:
encrypted_doc.write(ciphered_string)
# output cipher and reversed cipher
with open("encrypted.txt") as f:
t = f.read()
print(t)
print(t.translate(revmap))
看:
输出print(t)
:
EILKNPgOPNEJCiEILKNPgKOii]g(KKGOgBKNgPDAgBENOPg
LUgBEHAgEJgPDAgyQNNAJPgzENgwJzgPNwJOHwPAOgEPiBKNgNKKP zENO BEHAOgEJgKO
SwHG|\
\}iggggBEHAJwIAg2g6BgBKNgBgEJgBEHAOgEBgB
AJzOSEPD|\
LU\}86m8iiODEBPg2goooog]gEJP|EJLQP|\!JPANgwgODEBPgJQIxANgBKNgzKyQIAJPg\}}iiODEBPaxUg2gODEBPg_gHAJ|OPNEJC
LNEJPwxHA}g]gOKgEPgSKNGOgBKNgODEBPOgKBgnmmmmiIwLLANg2gOPN
IwGAPNwJO|gOPNEJC
LNEJPwxHA giggggggggggggggggggggggggOPNEJC
LNEJPwxHA6ODEBPaxU8g gOPNEJC
LNEJPwxHA6ODEBPaxU8}iiNARIwLg2gOPN
IwGAPNwJO|gOPNEJC
LNEJPwxHA6ODEBPaxU8g gOPNEJC
LNEJPwxHA6ODEBPaxU8 iggggggggggggggggggggggggOPNEJC
LNEJPwxHAg}ii]gPNwJOHwPAgzKyQIAJPOizKyaHEOP268iSEPDgKLAJ|BEHAJwIA}gwOgBiggggyELDANAzaOPNEJCg2gB
NAwz|}
PNwJOHwPA|IwLLAN}iiSEPDgKLAJ|\AJyNULPAz
PTP\ \S\}gwOgAJyNULPAzazKygiggggAJyNULPAzazKy
SNEPA|yELDANAzaOPNEJC}ii]gKQPLQPgyELDANgwJzgNARANOAzgyELDANiSEPDgKLAJ|\AJyNULPAz
PTP\}gwOgBiggggPg2gB
NAwz|}iggggLNEJP|P}iggggLNEJP|P
PNwJOHwPA|NARIwL}}
输出print(t.translate(revmap))
:
import string
import os
# Looks for the first -py file in the current dir and translates it:
for root,dirs,files in os-walk("-/"):
filename = [f for f in files if f-endswith("-py")][0]
shift = 2222 # int(input("Enter a shift number for document: "))
shift_by = shift % len(string-printable) # so it works for shifts of 10000
mapper = str-maketrans( string-printable,
string-printable[shift_by:] + string-printable[:shift_by])
revmap = str-maketrans( string-printable[shift_by:] + string-printable[:shift_by],
string-printable )
# translate documents
doc_list=[]
with open(filename) as f:
ciphered_string = f-read()-translate(mapper)
with open("encrypted-txt","w") as encrypted_doc:
encrypted_doc-write(ciphered_string)
# output cipher and reversed cipher
with open("encrypted-txt") as f:
t = f-read()
print(t)
print(t-translate(revmap))
推荐阅读
- sql-server - 在打开查询中强制转换 DB2 列以接受多语言字符
- python - 如何在 gitlab (CI/CD) 上使用 python 和 mongodb
- vim - vim逃犯如何在添加文件时处理提交消息?
- scala - 在 Spark SQL 中使用窗口函数结束日期记录
- javascript - JQuery DataTables Columns 使用数据自动初始化
- r - 如何在 R 中绘制回归预测的结果
- node.js - Angular HTTP Header 超过了 Node 的 HTTP_MAX_HEADER_SIZE?
- ios - 如何管理后台任务 iOS
- r - 在数据框中查找重复项并返回每个重复记录的计数
- javascript - 为什么 Chrome DevTools Screenshot 在一开始(1ms)就得到完整呈现的网页?