我已经编写了这段代码:
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
我在做什么错了?
答案 0 :(得分:1)
您的代码至少存在两个问题:
pop(maxpos)
之后,如果minpos
,minpos > maxpos
可能不再指向正确的字符;特别是,如果minpos
是(是)字符串中的最后一个位置,甚至可能导致索引错误replace(maximum, minimum)
,然后是replace(minimum, maximum)
,则所有 maximum
和 minimum
都将结束以maximum
相反,我建议使用collections.Counter
和str.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:'