非可視文字を削除する方法をPythonに尋ねる
Pythonでは正規表現で制御文字を取り除くことができます。以下にそのサンプルコードを示します。
import re
def remove_invisible_chars(text):
invisible_chars = re.compile('[\x00-\x1F\x7F]')
return invisible_chars.sub('', text)
text = 'This is a test string with \t invisible characters.'
clean_text = remove_invisible_chars(text)
print(clean_text)
コードを実行すると、出力結果は次のとおりです。
This is a test string with invisible characters.
この例では、不可視文字の範囲に一致させる正規表現[\x00-\x1F\x7F]を使用しました。次に、一致した不可視文字を空文字に置き換えるsub()関数を使用して、これらの不可視文字を削除します。