簡體   English   中英

從 python 中的字符串中去除非字母數字字符,但保留特殊字符

[英]Strip Non alpha numeric characters from string in python but keeping special characters

我知道 StackOverflow 上也有人問過類似的問題。 我試圖調整一些方法,但我無法讓任何東西發揮作用,這符合我的需要:

給定一個python 字符串,我想刪除每個非字母數字字符 -但是-留下任何特殊字符,如µ æ Å Ç ß ...這甚至可能嗎? 使用正則表達式我嘗試了這個的變體

re.sub(r'[^a-zA-Z0-9: ]', '', x) # x is my string to sanitize

但它比我想要的更多。 我想要的一個例子是:

Input:  "A string, with characters µ, æ, Å, Ç, ß,... Some    whitespace  confusion  ?"
Output: "A string with characters µ æ Å Ç ß Some whitespace confusion"

這甚至可以在不復雜的情況下實現嗎?

使用 \w 並設置 UNICODE 標志。 這也將匹配下划線,因此您可能需要單獨處理。

http://docs.python.org/library/re.html的詳細信息。

編輯:這是一些實際的代碼。 它將保留 unicode 字母、unicode 數字和空格。

import re
x = u'$a_bßπ7: ^^@p'
pattern = re.compile(r'[^\w\s]', re.U)
re.sub(r'_', '', re.sub(pattern, '', x))

如果您不使用 re.U,那么 ß 和 π 字符將被刪除。

抱歉,我想不出用一個正則表達式來做到這一點的方法。 如果可以,您可以發布解決方案嗎?

消除“標點符號,其他” Unicode 類別中的字符。

# -*- coding: utf-8 -*-

import unicodedata

# This removes punctuation characters.
def strip_po(s):
  return ''.join(x for x in s if unicodedata.category(x) != 'Po')

# This reduces multiple whitespace characters into a single space.
def fix_space(s):
  return ' '.join(s.split())

s = u'A string, with characters µ, æ, Å, Ç, ß,... Some    whitespace  confusion  ?'
print fix_space(strip_po(s))

如果您對 Unicode Consortium 對字母或數字的分類感到滿意,這是一種無需 RegEx 或導入內置插件之外的任何內容的簡單方法:

filter(unicode.isalnum, u"A string, with characters µ, æ, Å, Ç, ß,... Some    whitespace  confusion  ?")

如果您有str而不是unicode ,則需要先對其進行編碼。

您必須更好地定義特殊字符的含義。 有某些標志可以將空格、非空格、數字等內容分組,並針對特定的語言環境進行操作。 有關詳細信息,請參閱http://docs.python.org/library/re.html

但是,由於這是逐個字符的操作,您可能會發現簡單地明確指定每個字符會更容易,或者,如果要排除的字符數較少,則編寫一個僅排除這些字符的表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM