【问题标题】:Python Filtering String Text to Remove Picture CharactersPython过滤字符串文本以删除图片字符
【发布时间】:2020-06-20 07:17:13
【问题描述】:

在 Python 中过滤文本的最佳方法是什么,以便我只包含数字、大写/小写字母、所有标点符号和换行符、制表符等字符。

比如我可能有下面的文字,想去掉图片,但是链接、标点、字母、数字都可以:

????第 19 集现已上映!???? ????Pasta Go Go Food Review????车内烛光晚餐! PASTA LA VISTA 点击链接 B…

我查看了正则表达式,但不确定它是如何工作的。我正在尝试重新匹配。

看起来翻译表可能是要走的路,但它们似乎不能通过排除来工作。我想定义我想要的字符集并删除其他任何内容。

【问题讨论】:

标签: python python-3.x string


【解决方案1】:

unicodedata 模块将为您提供此处列出的 unicode 类别:https://unicodebook.readthedocs.io/unicode.html#categories。表情符号是“所以”。您可能还想过滤其他类别,但至少要过滤

>>> import unicodedata
>>> text = "?Episode 19 is OUT NOW!? ?Pasta Go Go Food Review? Candle Light Dinner in the Car! PASTA LA VISTA Click Link B…"
>>> filtered = "".join(c for c in text if "So" not in unicodedata.category(c))
>>> filtered
'Episode 19 is OUT NOW! Pasta Go Go Food Review Candle Light Dinner in the Car! PASTA LA VISTA Click Link B…'

【讨论】:

    【解决方案2】:

    快速而肮脏的解决方案是将字符串转换为 ascii,忽略所有非 ascii 字符

    unicode_string.encode('ascii', 'ignore')
    

    这仅适用于英语...

    【讨论】:

      猜你喜欢
      • 2012-06-26
      • 2019-02-17
      • 2016-09-30
      • 2019-12-27
      • 1970-01-01
      • 2014-03-29
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多