索引器:弹出索引超出范围

2024-04-20 05:58:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这样的代码:

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

我做错什么了?你知道吗


Tags: 代码textinforindex字母popfile
1条回答
网友
1楼 · 发布于 2024-04-20 05:58:07

您的代码至少有两个问题:

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

相反,我建议使用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:'

相关问题 更多 >