替换一行中多次出现的单引号字符串

问题描述 投票:0回答:1

我正在尝试用 Python 编写一个混淆器。有一个现成的加密算法,我将其导入为

import crypter
,混淆器的任务是将 crypter.
Cesar.decrypt(word)
粘贴到另一个 python 文件中,而不是正则表达式
r"'(.+? )'"
所表示的任何字符串(用单引号引起来) 。 操作逻辑:

  1. 打开文件逐行读取。
  2. 在单引号括起来的字符串
    r"'(.+?)'"
    中查找。
  3. 如果该行包含 ' ' 中的文本,则将其替换为
    crypter.Cesar.decrypt(cipher)
    ,其中 cipher 是通过 crypter.Cesar.crypt(word) 转换的 ' ' 中的文本。
  4. 将此修改后的行保存到文件中。
  5. 继续到文件末尾

这是起始文件:

dog = 'The dog is a domesticated descendant of the wolf'
animals = {
    'cow': 'Cattle (Bos taurus) are large, domesticated, bovid ungulates',
    'cat': 'The cat (Felis catus), commonly referred to as the domestic cat or house cat, is the only domesticated species in the family Felidae',
    'Tiger': 'The tiger (Panthera tigris) is the largest living cat species and a member of the genus Panthera',
}

这是我的代码:

import crypter
import re

file = open("test.txt", "r")
file_1 = open("test_1.txt", "a")
for line in file:
    words = re.findall(r"('.+?')", line)
    if len(words) > 0:
        for word in words:
            cipher = crypter.Cesar.crypt(word)
            new_line = line.replace(word, f"crypter.Cesar.decrypt({cipher})")
            file_1.write(new_line)
    else:
        file_1.write(line)

一切正常,直到一行中有两个(也许更多)“..”:

dog = crypter.Cesar.decrypt('Tif eph jt b epnftujdbufe eftdfoebou pg uif xpmg')
animals = {
    crypter.Cesar.decrypt('dpx'): 'Cattle (Bos taurus) are large, domesticated, bovid ungulates',
    'cow': crypter.Cesar.decrypt('Cbuumf (Bpt ubvsvt) bsf mbshf, epnftujdbufe, cpwje vohvmbuft'),
    crypter.Cesar.decrypt('dbu'): 'The cat (Felis catus), commonly referred to as the domestic cat or house cat, is the only domesticated species in the family Felidae',
    'cat': crypter.Cesar.decrypt('Tif dbu (Ffmjt dbuvt), dpnnpomz sfgfssfe up bt uif epnftujd dbu ps ipvtf dbu, jt uif pomz epnftujdbufe tqfdjft jo uif gbnjmz Ffmjebf'),
    crypter.Cesar.decrypt('Tjhfs'): 'The tiger (Panthera tigris) is the largest living cat species and a member of the genus Panthera',
    'Tiger': crypter.Cesar.decrypt('Tif ujhfs (Pbouifsb ujhsjt) jt uif mbshftu mjwjoh dbu tqfdjft boe b nfncfs pg uif hfovt Pbouifsb'),
}

我知道Python中的文本不变性,但一定有某种方法可以做到这一点?

python string obfuscation
1个回答
0
投票

据我所知,有两个问题:

  • new_line = line.replace...
    从每个单词的原始行开始。
  • 您将每个单词的 new_line 写入文件:仅写入一次完全翻译的 new_line。 这是一些固定代码:
import crypter
import re

file = open("test.txt", "r")
file_1 = open("test_1.txt", "a")
for line in file:
    words = re.findall(r"('.+?')", line)
    if len(words) > 0:
        new_line = line
        for word in words:
            cipher = crypter.Cesar.crypt(word)
            new_line = new_line.replace(word, f"crypter.Cesar.decrypt({cipher})")
        file_1.write(new_line)
    else:
        file_1.write(line)
© www.soinside.com 2019 - 2024. All rights reserved.