import collections
import string
with open('cipher.txt') as f:
f = f.read().replace(' ', '').replace('\n','').lower()
f = f.strip(string.punctuation)
cnt = collections.Counter(f.replace(' ', ''))
for letter in sorted(cnt):
print(letter, cnt[letter])
怎么去掉标点符号!!我不知道该把这条线放在哪里?
有人可以修改我的代码以删除除字母之外的所有内容吗?谢谢
Use str.translate()删除代码点;任何映射到的代码点None
已移除:
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
f.translate(remove)
The dict.fromkeys()
类方法可以轻松创建将所有键映射到的字典None
.
Demo:
>>> import string
>>> remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
>>> sample = 'The quick brown fox, like, totally jumped, man!'
>>> sample.translate(remove)
'Thequickbrownfoxliketotallyjumpedman'
调整为您的代码:
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
with open('cipher.txt') as inputfile:
f = inputfile.read().translate(remove)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)