梗概
中文及中文标点使用unicode,英文及英文标点和空格换行等使用ascii
工具类
# 给予一个字符串,传回一个由unicode组成的列表,列表中没有对标点符号和字母进行处理
def getList(string):
strings = string.encode('unicode-escape').decode()
lists = strings.split('\\u')
while '' in lists:
lists.remove('')
return lists
def doChinese(string,offset):
# 对上面方法传回的形如“ 6211 ”Unicode字符串进行偏移操作,不对标点和字母操作
if len(string) == 4 and '\n' not in string:
num = hex(int(string,16)+offset)[2:]
sstring = '\\u{}'.format(num).encode('utf-8').decode("unicode_escape")
return sstring
# 对超过unicode范围的其他标点和字母操作(英文标点不偏移,就是不改变)
elif len(string) > 4 and '\n' not in string:
lists = string[0:4]
num = hex(int(lists,16)+offset)[2:]
splString = string[4:]
listss = []
for i in splString:
listss.append(rp(i,offset))
sstring = '\\u{}'.format(num).encode('utf-8').decode("unicode_escape")
sstring += ''.join(listss)
lll = list(sstring)
for i in range(len(lll)-1):
if(lll[i] == '\\' and lll[i+1] == 'n'):
lll[i] = ''
lll[i+1] = '\n'
sstring = ''.join(lll)
return sstring
# 对英文字母的偏移操作
# def rp(st,offset):
# if(ord(st)>64 and ord(st)<88):
# return chr(ord(st)+offset)
# elif(ord(st)>87 and ord(st)<91):
# return chr(ord(st)+offset-26)
# elif(ord(st)>96 and ord(st)<120):
# return chr(ord(st)+offset)
# elif(ord(st)>119 and ord(st)<123):
# return chr(ord(st)+offset-26)
# else:
# return st
# 对所有非中文通过ascii偏移
def rp(st,offset):
return chr(ord(st)+offset)
读取文件并使用工具类方法写入文件
import operate as op
def KS(offset):
fread = open("C:\\Users\\DELL\\Desktop\\ss.txt",encoding='utf-8')
fwrite = open("C:\\Users\\DELL\\Desktop\\kk.txt",mode='w',encoding='utf-8')
for line in fread.readlines():
lists = op.getList(line)
string = ''
for i in lists:
string += (op.doChinese(i,offset))
fwrite.write(string)
fwrite.flush()
fwrite.close()
fread.close()
KS(4)
如上将下列文字加密
得到:
再将偏移量改为加密偏移量的负数,同一逻辑写入另一个文件
KS(-4)
得到:
完成!