【问题标题】:How to strip punctuation from a text file [duplicate]如何从文本文件中删除标点符号[重复]
【发布时间】:2013-09-05 09:12:16
【问题描述】:
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])

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

【问题讨论】:

  • strip 方法只删除字符串开头和结尾的字符。另外,我认为打开 f 然后重新分配 f 是一个坏主意。
  • @AshwiniChaudhary:有趣的是,该页面没有 Python 3 解决方案。我加了一个。

标签: python python-3.x


【解决方案1】:

使用str.translate() 删除代码点;任何映射到None 的代码点都被删除:

remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
f.translate(remove)

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'

已根据您的代码进行了调整:

remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))

with open('cipher.txt') as inputfile:
    f = inputfile.read().translate(remove)

【讨论】:

  • 如何在我的代码中实现这一点? :)
  • @samir:正如我发布的那样。
  • 有没有办法同时删除所有数字?抱歉所有问题:/
  • @samir:将string.digits 添加到删除的字符集中很容易,不是吗?我已经在示例代码中展示了如何连接多个字符串。
  • string.punctuation + string.digits 还是不行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2019-03-29
  • 1970-01-01
  • 2016-09-01
  • 2022-01-25
  • 2019-08-04
相关资源
最近更新 更多