IndexError:弹出索引超出范围

时间:2019-02-12 15:07:20

标签: python python-3.x

我已经编写了这段代码:

filename=input("Give the name of a file,for example example.txt\n")
file = open(filename, "r+") 
text = file.read()
frequency = []
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
for letter in alphabet:
    frequency.append(text.count(letter))
for i in range(13):
    maximum = max(frequency)
    minimum = min(frequency)
    maxpos = frequency.index(maximum)
    minpos = frequency.index(minimum)
    text = text.replace (str(maximum), str(minimum))
    text = text.replace (str(minimum), str(maximum))
    alphabet.pop(maxpos)
    alphabet.pop(minpos)
    frequency.pop(maxpos)
    frequency.pop(minpos)
file.close()

该代码应从文件中读取文本,然后用最不常见的字母替换最常见的字母,反之亦然,然后用第二个最不常见的字母替换第二最常见的字母,依此类推。 但是,我遇到了这个问题:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\file.py", line 16, in <module>
    alphabet.pop(minpos)
IndexError: pop index out of range

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

您的代码至少存在两个问题:

  • pop(maxpos)之后,如果minposminpos > maxpos可能不再指向正确的字符;特别是,如果minpos是(是)字符串中的最后一个位置,甚至可能导致索引错误
  • 如果您的第一个replace(maximum, minimum),然后是replace(minimum, maximum),则所有 maximum minimum都将结束以maximum
  • 开头

相反,我建议使用collections.Counterstr.translate

import collections, string
text = """This code is supposed to read a text from a file,then replace the most common letter with the least common letter and vice versa,then replace the second most common letter with the second least common letter and so on. However,I get this problem:""".lower()

counts = collections.Counter(text)
srtd = ''.join(sorted(set(text).intersection(string.ascii_lowercase), key=counts.get))
# 'xbugfvwpdilcarhnmsote'
result = text.translate(str.maketrans(srtd, srtd[::-1]))
# 'bwcg iuax cg gorrugxa bu pxda d bxeb mpuf d mclx,bwxv pxrldix bwx fugb iuffuv lxbbxp hcbw bwx lxdgb iuffuv lxbbxp dva ncix nxpgd,bwxv pxrldix bwx gxiuva fugb iuffuv lxbbxp hcbw bwx gxiuva lxdgb iuffuv lxbbxp dva gu uv. wuhxnxp,c sxb bwcg rputlxf:'