请帮我解决以下错误

时间:2011-02-08 19:12:17

标签: python

下面是错误详情

bias = ord(密码[position%password_length])

缩进错误=预期缩进块

   1.
      '''crypt module
   2.

   3.
      Contains a simple function, "crypt", that will both encrypt and decrypt a string
   4.
      of text by XORing it with a password or phrase.'''
   5.

   6.
      import StringIO
   7.

   8.
      def crypt(text, password):
   9.
      '''Encrypts or decrypts a string of text.
  10.

  11.
      text: any string
  12.
      password: the word or phrase you want to encrypt/decrypt with'''
  13.

  14.
      old = StringIO.StringIO(text)
  15.
      new = StringIO.StringIO(text)
  16.
      password_length = len(password)
  17.

  18.
      for position in xrange(len(text)):
  19.
      bias = ord(password[position % password_length]) # Get next bias character from password
  20.

  21.
      old_char = ord(old.read(1))
  22.
      new_char = chr(old_char ^ bias) # Get new charactor by XORing bias against old character
  23.

  24.
      new.seek(position)
  25.
      new.write(new_char)
  26.

  27.
      new.seek(0)
  28.
      return new.read()
  29.

  30.
      def _file_test():
  31.
      '''A testing function'''
  32.

  33.
      str1 = '''A list of quotes from Grade School Essays on the History of Classical Music:
  34.
      "J.S. Bach died from 1750 to the present"
  35.
      "Agnus Dei was a woman composer famous for her church music."
  36.
      "Refrain means don't do it. A refrain in music is the part you better not try to sing."
  37.
      "Handel was half German, half Italian, and half English. He was rather large."
  38.
      "Henry Purcell is a well-known composer few people have ever heard of."
  39.
      "An opera is a song of bigly size."
  40.
      "A harp is a nude piano."
  41.
      "A virtuoso is a musician with real high morals."
  42.
      "Music sung by two people at the same time is called a duel."
  43.
      "I know what a sextet is but I'd rather not say."
  44.
      "Most authorities agree that music of antiquity was written long ago."
  45.
      "My favorite composer is opus."
  46.
      "Probably the most marvelous fugue was between the Hatfields and the McCoys."
  47.
      "My very best liked piece is the bronze lullaby."'''
  48.

  49.
      plain_text_name = 'Music101.txt'
  50.
      encrypted_text_name = 'Music101.enc'
  51.

  52.
      # Save the string as a normal text file
  53.
      file_out = open(plain_text_name, 'w')
  54.
      file_out.write(str1)
  55.
      file_out.close()
  56.

  57.
      # Let's use a fixed password for testing
  58.
      password = 'Cold Roses'
  59.

  60.
      # Encrypt the text file
  61.
      file_in = open(plain_text_name)
  62.
      file_out = open(encrypted_text_name, 'wb')
  63.
      file_out.write(crypt(file_in.read(), password))
  64.
      file_in.close()
  65.
      file_out.close()
  66.

  67.
      # Encrypted file shows a hot mess
  68.
      file_in = open(encrypted_text_name, 'rb')
  69.
      print(repr(file_in.read()))
  70.
      print('-' * 80)
  71.
      file_in.close()
  72.

  73.
      # Decrypt the recently encrypted text file and print it
  74.
      file_in = open(encrypted_text_name)
  75.
      print crypt(file_in.read(), password)
  76.
      file_in.close()
  77.

  78.
      # Run tests when this file is run as a program instead of being imported
  79.
      if __name__ == '__main__':
  80.
      _file_test()

2 个答案:

答案 0 :(得分:3)

删除这些行号,并修复这些缩进。你的代码在没有缩进时是不可用的,但这是一个带有格式的工作版本:

'''crypt module

Contains a simple function, "crypt", that will both encrypt and decrypt a string

of text by XORing it with a password or phrase.'''

import StringIO

def crypt(text, password):
  '''Encrypts or decrypts a string of text.



  text: any string

  password: the word or phrase you want to encrypt/decrypt with'''



  old = StringIO.StringIO(text)
  new = StringIO.StringIO(text)
  password_length = len(password)


  for position in xrange(len(text)):
    bias = ord(password[position % password_length]) # Get next bias character from password

  old_char = ord(old.read(1))
  new_char = chr(old_char ^ bias) # Get new charactor by XORing bias against old character

  new.seek(position)
  new.write(new_char)

  new.seek(0)

  return new.read()



def _file_test():
  '''A testing function'''



  str1 = '''A list of quotes from Grade School Essays on the History of Classical Music:
  "J.S. Bach died from 0 to the present"
  "Agnus Dei was a woman composer famous for her church music."
  "Refrain means don't do it. A refrain in music is the part you better not try to sing."
  "Handel was half German, half Italian, and half English. He was rather large."
  "Henry Purcell is a well-known composer few people have ever heard of."
  "An opera is a song of bigly size."
  "A harp is a nude piano."
  "A virtuoso is a musician with real high morals."
  "Music sung by two people at the same time is called a duel."
  "I know what a sextet is but I'd rather not say."
  "Most authorities agree that music of antiquity was written long ago."
  "My favorite composer is opus."
  "Probably the most marvelous fugue was between the Hatfields and the McCoys."
  "My very best liked piece is the bronze lullaby."'''

  plain_text_name = 'Music.txt'
  encrypted_text_name = 'Music.enc'

  # Save the string as a normal text file

  file_out = open(plain_text_name, 'w')
  file_out.write(str1)
  file_out.close()

  # Let's use a fixed password for testing

  password = 'Cold Roses'

  # Encrypt the text file

  file_in = open(plain_text_name)
  file_out = open(encrypted_text_name, 'wb')
  file_out.write(crypt(file_in.read(), password))
  file_in.close()
  file_out.close()

  # Encrypted file shows a hot mess

  file_in = open(encrypted_text_name, 'rb')
  print(repr(file_in.read()))
  print('-' * 80)

  file_in.close()

  # Decrypt the recently encrypted text file and print it

  file_in = open(encrypted_text_name)
  print crypt(file_in.read(), password)

  file_in.close()



# Run tests when this file is run as a program instead of being imported

if __name__ == '__main__':
  _file_test()

这是输出:

> python test.py

    'A list of quotes from Grade School Essays on the History of Classical Music:\n  "J.S. Bach died from 0 to the present"\n  "Agnus Dei was a woman composer famous for her church music."\n  "Refrain means don\'t do it. A refrain in music is the part you better not try to sing."\n  "Handel was half German, half Italian, and half English. He was rather large."\n  "Henry Purcell is a well-known composer few people have ever heard of."\n  "An opera is a song of bigly size."\n  "A harp is a nude piano."\n  "A virtuoso is a musician with real high morals."\n  "Music sung by two people at the same time is called a duel."\n  "I know what a sextet is but I\'d rather not say."\n  "Most authorities agree that music of antiquity was written long ago."\n  "My favorite composer is opus."\n  "Probably the most marvelous fugue was between the Hatfields and the McCoys."\n  "My very best liked piece is the bronze lullaby.$'
    --------------------------------------------------------------------------------
    A list of quotes from Grade School Essays on the History of Classical Music:
      "J.S. Bach died from 0 to the present"
      "Agnus Dei was a woman composer famous for her church music."
      "Refrain means don't do it. A refrain in music is the part you better not try to sing."
      "Handel was half German, half Italian, and half English. He was rather large."
      "Henry Purcell is a well-known composer few people have ever heard of."
      "An opera is a song of bigly size."
      "A harp is a nude piano."
      "A virtuoso is a musician with real high morals."
      "Music sung by two people at the same time is called a duel."
      "I know what a sextet is but I'd rather not say."
      "Most authorities agree that music of antiquity was written long ago."
      "My favorite composer is opus."
      "Probably the most marvelous fugue was between the Hatfields and the McCoys."
      "My very best liked piece is the bronze lullaby.

正则表达式和快速按空格键可以创造奇迹;)

答案 1 :(得分:2)

python程序的缩进是其含义的一部分。例如,

for i in range(20):
    t = i
    print i

打印数字0到19,但

for i in range(20):
    t = i
print i

仅打印19(Python 2)或提供可变范围错误(Python 3)。在第一个例子中,缩进意味着'print i'在循环内;在第二个,它不是。

在您给定的代码中,第18行和第19行看起来像

for position in xrange(len(text)):
bias = ord(password[position % password_length])

这是一个没有任何内容的循环,后跟一个单独的语句。在Python中没有任何内容的循环是非法的,并导致错误消息。

应该是

for position in xrange(len(text)):
    bias = ord(password[position % password_length])

沿着要编码的文本进行迭代。

在任何情况下,crypt()函数都比它需要的复杂得多;它可以被

取代
from itertools import izip, cycle

def crypt(text, password):
    """Encrypts or decrypts a string of text.

    @param text:     string, text to encrypt
    @param password: string, encryption key
    """
    return ''.join(chr(ord(t)^ord(p)) for t,p in izip(text, cycle(password)))

和test_crypt()同样可以简化,

import testwrap

def test_crypt():
    """Test the encryption function.
    """

    test_str = textwrap.dedent("""
        A list of quotes from Grade School Essays on the History of Classical Music:
        "J.S. Bach died from 1750 to the present"
        "Agnus Dei was a woman composer famous for her church music."
        "Refrain means don't do it. A refrain in music is the part you better not try to sing."
        "Handel was half German, half Italian, and half English. He was rather large."
        "Henry Purcell is a well-known composer few people have ever heard of."
        "An opera is a song of bigly size."
        "A harp is a nude piano."
        "A virtuoso is a musician with real high morals."
        "Music sung by two people at the same time is called a duel."
        "I know what a sextet is but I'd rather not say."
        "Most authorities agree that music of antiquity was written long ago."
        "My favorite composer is opus."
        "Probably the most marvelous fugue was between the Hatfields and the McCoys."
        "My very best liked piece is the bronze lullaby."
    """)

    pw = 'Cold Roses'
    encrypted = crypt(test_str, pw)
    decrypted = crypt(encrypted, pw)

    if decrypted != test_str:
        print 'Test failed!'
    else:
        print decrypted