[Python Challenge通关]第2关

第 2 关

挑战地址,点我[Python Challenge通关]第2关

问题

[Python Challenge通关]第2关

recognize the characters. maybe they are in the book,

but MAYBE they are in the page source.

分析

根据提示我们需要右键查看页面源码,我们可以看到有一段提示,和一堆字符:

<!--
find rare characters in the mess below:
-->

<!--
%%[email protected]_$^__#)^)&!_+]!*@&^}@[@%]()%+$&[([email protected]%+%$*^@$^!+]!&_#)_*}{}}!}_]$[%}@[{[email protected]#_^{*

提示告诉我们需要找出一堆字符中的稀有字符,那就开始吧:

import collections

text = '''复制那一堆字符进来'''
c = collections.Counter(text)
print(c.most_common())
# [(')', 6186), ('@', 6157), ('(', 6154), (']', 6152), ('#', 6115), ('_', 6112), ('[', 6108), ('}', 6105), ('%', 6104), ('!', 6079), ('+', 6066), ('$', 6046), ('{', 6046), ('&', 6043), ('*', 6034), ('^', 6030), ('\n', 1219), ('e', 1), ('q', 1), ('u', 1), ('a', 1), ('l', 1), ('i', 1), ('t', 1), ('y', 1)]

我们使用了 collections 包中的 Counter 来统计字符串中字符出现的次数,从结果来看有几个只出现了 1 次的字符,这应该就是我们需要的稀有字符。我们过滤出来看看。

print(''.join([i[0] for i in c.items() if i[1]==1]))
# equality

得到一个单词 equality,用它来替换条当前页面 url http://www.pythonchallenge.com/pc/def/ocr.html 中的 ocr 即可进入下一关。

补充

当然我们也可以使用 dict 来进行统计。

wordcounts = {}
for c in text:
    wordcounts[c] = wordcounts.get(c, 0) + 1
print(wordcounts)
print(''.join([i[0] for i in wordcounts.items() if i[1]==1]))

参考资源:

  1. https://docs.python.org/3/library/collections.html#collections.Counter
  2. https://docs.python.org/3/library/stdtypes.html#dict