【问题标题】:what is wrong with my encoding/cipher code?我的编码/密码有什么问题?
【发布时间】:2012-06-06 10:38:09
【问题描述】:

我的代码用于替换某些字母(a 替换为 e,e 替换为 a,s 替换为 3)不起作用,但我不太确定错误是什么,因为它没有更改我的文本文件喂它。

pattern = "ae|ea|s3"

def encode(pattern, filename):
  message = open(filename, 'r+')
  output = []
  pattern2 = pattern.split('|')
  for letter in message:
    isfound = false
    for keypair in pattern2:
      if letter == keypair[0]: 
        output.append(keypair[1])
        isfound = true
      if isfound == true:
       break;
    if isfound == false:
      output.append(letter)

  message.close()  

我绞尽脑汁想弄明白这件事有一段时间了..

【问题讨论】:

标签: python encode encryption


【解决方案1】:

这是一个快速的实现,你需要自己修改它来读取文件等:

def encode(pattern, string):
    rep = {}
    for pair in pattern.split("|"):
        rep[pair[0]] = pair[1]

    out = []
    for c in string:
        out.append(rep.get(c, c))

    return "".join(out)

print encode("ae|ea|s3", "Hello, this is my default string to replace")
#output => "Hallo, thi3 i3 my dafeult 3tring to rapleca"

如果你想修改一个文件,你需要专门告诉你的程序写入文件。简单地附加到您的输出变量不会改变它。

【讨论】:

    【解决方案2】:

    它不会更改文本文件,因为您没有将文本文件替换为您创建的output。相反,此函数创建 output 字符串并将其放在函数末尾。从函数返回output 字符串并将其存储在外部,或者通过写入文件而不附加来替换函数中的文件。

    由于这看起来像是一个练习,我宁愿不添加代码来完成它,因为您可能会从自己编写函数中学到更多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 2011-07-28
      相关资源
      最近更新 更多