2014-02-06 77 views
3

上周之前,我对Python的使用经验非常有限,因为我们的网络上的大型数据库文件非常有限,突然之间我被迫进入尝试从html表格中提取信息的世界。python lxml xpath返回带文本的列表中的转义字符

经过大量阅读后,我选择使用Python 2.7的lxml和xpath来检索有问题的数据。

xpath = "//table[@id='resultsTbl1']/tr[position()>1]/td[@id='row_0_partNumber']/child::text()" 

这产生了以下列表::我已用下面的代码检索一个场

['\r\n\t\tBAR18FILM/BKN', '\r\n\t\t\r\n\t\t\t', '\r\n\t\t\t', '\r\n\t\t\t', '\r\n\t\t\t', '\r\n\t\t\t', '\r\n\t\t\t\r\n\t\t'] 

我确认的CR/LF和标签转义字符,我想知道如何避免它们?

回答

0

这些字符是XML文档的一部分,这就是它们被返回的原因。你无法避免它们,但你可以将它们去除。你可以把每个项目.strip()方法返回:

results = [x.strip() for x in results] 

这会剥夺开头和结尾的空白。没有看到你的实际代码和数据,很难给出一个好的答案。

例如,假设这个脚本:

#!/usr/bin/python 

from lxml import etree 

with open('data.xml') as fd: 
    doc = etree.parse(fd) 

results = doc.xpath(
    "//table[@id='results']/tr[position()>1]/td/child::text()") 

print 'Before stripping' 
print repr(results) 

print 'After stripping' 
results = [x.strip() for x in results] 
print repr(results) 

而这个数据:

<doc> 
    <table id="results"> 
    <tr> 
     <th>ID</th><th>Name</th><th>Description</th> 
    </tr> 

    <tr> 
     <td> 
     1 
     </td> 
     <td> 
     Bob 
     </td> 
     <td> 
     A person 
     </td> 
     </tr> 
    <tr> 
     <td> 
     2 
     </td> 
     <td> 
     Alice 
     </td> 
     <td> 
     Another person 
     </td> 
    </tr> 
    </table> 
</doc> 

我们得到这些结果:

Before stripping 
['\n\t\t\t1\n\t\t\t', '\n\t\t\tBob\n\t\t\t', '\n\t\t\tA person\n\t\t\t', '\n\t\t\t2\n\t\t\t', '\n\t\t\tAlice\n\t\t\t', '\n\t\t\tAnother person\n\t\t\t'] 
After stripping 
['1', 'Bob', 'A person', '2', 'Alice', 'Another person']