解释我的python挑战解决方案有什么问题吗?

时间:2014-01-13 11:32:28

标签: python python-2.7

我正在尝试在view-source:http://www.pythonchallenge.com/pc/def/ocr.html

中找到一个特殊字符

这是我的代码:

f = open('file.txt')
lines = f.read()
k = ''.join(lines)
stat = ''
for i in k:
    if i in '#&@$!*^{}_()*+[]%':
        stat=stat+''
    else:
        stat=stat+i

print(stat)

我得到的答案是“平等”,但话语相差甚远。为什么会这样?因为我没有为其他角色添加任何空间。

2 个答案:

答案 0 :(得分:5)

您没有跳过文件中的换行符:

for i in k:
    if i not in '#&@$!*^{}_()*+[]%\n':
        stat=stat+i

请注意,在特殊字符字符串中为任何内容添加空字符串几乎没有意义。仅在该字符串中的字符时附加。

无论如何你已经找到了解决方案,但实际上找到罕见的角色可以更好地应对挑战:

from collections import Counter
import requests  # external library but much more convenient than urllib2

r = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')
text = r.text.rsplit('<!--', 1)[-1].rsplit('-->', 1)[0]  # extract comment
counts = Counter(text)
rare = {c for c in counts if counts[c] < 5}
print ''.join([c for c in text if c in rare])

其中罕见仅为一次,真的。

答案 1 :(得分:0)

你没有跳过换行符,这就是你得到一种“拉伸”输出的原因。

以下是我尝试解决问题,将评论纳入您的问题:

f = open('file.txt')
data = f.read()
stat = ''
for i in data:
    if i in '#&@$!*^{}_()+[]%]\n':
        h=6
    else:
        stat=stat+i
print stat
相关问题