如何从python中的文件中删除空格以外的特殊字符? [英] How to remove special characters except space from a file in python?

查看:51
本文介绍了如何从python中的文件中删除空格以外的特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大量的文本(逐行显示),我想删除特殊字符,但要保留字符串的空间和结构.

I have a huge corpus of text (line by line) and I want to remove special characters but sustain the space and structure of the string.

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 使用此模式:

You can use this pattern, too, with 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 

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

Otherwise, you can store the final lines into a 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 ']

这篇关于如何从python中的文件中删除空格以外的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆