Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 请帮我解决下面的错误_Python - Fatal编程技术网

Python 请帮我解决下面的错误

Python 请帮我解决下面的错误,python,Python,下面是错误详细信息 bias=ord(密码[位置%password\u长度]) 缩进错误=应为缩进块 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.

下面是错误详细信息

bias=ord(密码[位置%password\u长度])

缩进错误=应为缩进块

   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()

删除这些行号,并修复这些缩进。如果代码未插入,则无法使用,但这里有一个带格式的工作版本:

'''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.

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

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

听起来Python在抱怨,因为代码中的某个地方缩进错误,但是粘贴的代码没有缩进。请更正您的格式,使其与您实际得到的内容相匹配(并去掉无意义的数字),然后有人将能够回答您的问题。我不确定哪里出了问题。我格式化了代码,看起来很有效…@AON在过去的几个月里,你问了8个问题,但没有接受任何答案。在堆栈溢出时,这是不受欢迎的。请花点时间阅读常见问题解答(链接在页面顶部)。然后回到你以前的问题,按照常见问题解答中的解释,在每个问题的最佳答案上打勾。此外,所有问题的标题都是“请帮助”。你不必在这里寻求帮助。只要问这个问题。问题标题应该让主题专家立即了解你的问题,并指导其他人是否能够回答。细节在问题中。这样你的问题会得到更好的答案。尽管OP可能不会接受你的答案,但你还是花了时间写了一个惊人的解释+1.因为她非常好。