膨大な量のテキスト(一行ずつ)があり、特殊文字を除去したいが、文字列のスペースや構造は維持したい。
hello? there A-Z-R_T(,**), world, welcome to python.
this **should? the next line#followed- by@ an#other %million^ %%like $this.
は、次のようになります。
hello there A Z R T world welcome to python
this should be the next line followed by another million like this
このパターンは、regex
でも使用できます。
import re
a = '''hello? there A-Z-R_T(,**), world, welcome to python.
this **should? the next line#followed- by@ an#other %million^ %%like $this.'''
for k in a.split("\n"):
print(re.sub(r"[^a-zA-Z0-9]+", ' ', k))
# Or:
# final = " ".join(re.findall(r"[a-zA-Z0-9]+", k))
# print(final)
出力します。
hello there A Z R T world welcome to python
this should the next line followed by an other million like this
編集します。
そうでなければ、最終行を list
に格納することができます。
final = [re.sub(r"[^a-zA-Z0-9]+", ' ', k) for k in a.split("\n")]
print(final)
出力します。
['hello there A Z R T world welcome to python ', 'this should the next line followed by an other million like this ']
特殊文字をNoneにマッピングする辞書の作成
d = {c:None for c in special_characters}
辞書を使って翻訳テーブルを作る。 テキスト全体を変数に読み込んで、テキスト全体にstr.translateを使用します。