Saya memiliki korpus teks yang sangat besar (baris demi baris) dan saya ingin menghapus karakter khusus tetapi mempertahankan ruang dan struktur string.
hello? there A-Z-R_T(,**), world, welcome to python.
this **should? the next line#followed- by@ an#other %million^ %%like $this.
seharusnya
hello there A Z R T world welcome to python
this should be the next line followed by another million like this
Anda juga bisa menggunakan pola ini, dengan 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)
Keluaran:
hello there A Z R T world welcome to python
this should the next line followed by an other million like this
Edit:
Jika tidak, Anda dapat menyimpan baris-baris terakhir ke dalam daftar
:
final = [re.sub(r"[^a-zA-Z0-9]+", ' ', k) for k in a.split("\n")]
print(final)
Keluaran:
['hello there A Z R T world welcome to python ', 'this should the next line followed by an other million like this ']
Saya pikir jawaban nfn neil sangat bagus ... tetapi saya hanya akan menambahkan regex sederhana untuk menghapus semua karakter tanpa kata, namun itu akan menganggap garis bawah sebagai bagian dari kata
print re.sub(r'\W+', ' ', string)
>>> hello there A Z R_T world welcome to python
Membuat kamus yang memetakan karakter khusus ke None
d = {c:None for c in special_characters}
Buat tabel terjemahan menggunakan kamus. Baca seluruh teks ke dalam variabel dan gunakan str.translate pada seluruh teks.