有没有更优雅的方法来重构此线性代码块?

时间:2019-03-28 06:41:05

标签: python refactoring

我为此课程分配了解决方案。本质上,这是一个凯撒密码,它将文件作为输入以及移位值,并输出“ 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()

我很好奇是否有办法减少必要的行数,或者使它更漂亮?感觉很笨拙。

1 个答案:

答案 0 :(得分:0)

您可以缩短此时间:

  • 使用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))