python - 如何从python中的文件中删除除空格之外的特殊字符?

标签 python regex string file string-formatting

<分区>

我有一个巨大的文本语料库(逐行),我想删除特殊字符但保留字符串的空间和结构。

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 

编辑:

否则,您可以将最后几行存储到列表中:

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 ']

关于python - 如何从python中的文件中删除除空格之外的特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358857/

相关文章:

python - 成交量加权移动平均线

javascript - 获取括号内的文本

python - 将数字与字母分开的正则表达式

regex - 继续在 perl 中换行

python - 从文本文件中查找具有最小值和最大值的行以及行号(获取值错误浮点类型)

python - 使用 scapy 将以太网填充添加到数据包

python - 启动 [Selenium] [Python] 后 Chrome 崩溃

python - 扭曲,如何将 "putChild()"带尾部斜杠?

javascript - 如何使用js删除json中特定索引处的字符?

MySQL SELECT 查询字符串分割搜索值