Python 如何从文本文件中删除标点符号

Python 如何从文本文件中删除标点符号,python,python-3.x,Python,Python 3.x,我如何去掉标点符号!!我不知道该把那条线放在哪里? 有人可以修改我的代码,删除除字母以外的所有内容吗?谢谢用于删除代码点;任何到None的代码点映射都将被删除: import collections import string with open('cipher.txt') as f: f = f.read().replace(' ', '').replace('\n','').lower() f = f.strip(string.punctuation) cnt = collecti

我如何去掉标点符号!!我不知道该把那条线放在哪里? 有人可以修改我的代码,删除除字母以外的所有内容吗?谢谢

用于删除代码点;任何到
None
的代码点映射都将被删除:

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])
使用
dict.fromkeys()
类方法可以轻松创建一个字典,将所有键映射到
None

演示:

根据您的代码进行调整:

>>> import string
>>> remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
>>> sample = 'The quick brown fox, like, totally jumped, man!'
>>> sample.translate(remove)
'Thequickbrownfoxliketotallyjumpedman'

strip
方法仅删除字符串开头和结尾的字符。另外,我认为以
f
的形式打开一些东西,然后重新分配
f
@AshwiniChaudhary是个坏主意:有趣的是,该页面没有Python 3解决方案。我添加了一个。如何在代码中实现此功能?:)@萨米尔:和我贴的一模一样。有没有办法把所有号码都删除?对所有的问题感到抱歉:/@samir:在删除的字符集中添加
字符串。数字
很容易,不是吗?我已经在示例代码中演示了如何连接多个字符串。
string.标点符号+string.digits
仍然不起作用?
>>> 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)