在Python中删除空格和不可打印的字符 [英] Removing spaces and non-printable character in Python

查看:625
本文介绍了在Python中删除空格和不可打印的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用lxml etree xpath方法处理xml文件.我的代码是

I am working with xml file using lxml etree xpath method. My code is

from lxml import etree
File="c:\file.xml"
doc=etree.parse(File)
alltext = doc.xpath('descendant-or-self::text()')
clump = "".join(alltext)
clump

我得到以下输出:

             "'\n\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\t\n\t\n\t\t\n\t\t\t\n\t\t\t\tIntroduction\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\t\tAccessibility\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\t\tOpening eBooks\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\

我想从输出中删除空格和所有制表符,所以我使用了另一个代码,但未能获得所需的输出
这是代码

I want to remove spaces and all tabs from output, so I use another code but failed to get the desired output
Here is that code

import string
filter(lambda x: x in string.printable, clump)

我只想从简介,可访问性,打开电子书"的输出中获取文本

I only want to get text from output which is "Introduction , Accessibilty , Opening eBooks"

推荐答案

如果您不介意使用regex进行操作:

If you don't mind to do it using regex:

import re
clump = re.sub(r'[\n\t]+', ' ', clump)

如果要删除其他任何字符,只需将其放在[]

If you want to put any other characters to remove, just place those inside the []

这篇关于在Python中删除空格和不可打印的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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