python - 在 Python 中处理 `
`

标签 python xml encoding beautifulsoup

问题背景:

我有一个 XML 文件,我正在将其导入 BeautifulSoup 并进行解析。一个节点有以下内容:

<DIAttribute name="ObjectDesc" value="Line1&#xD;&#xA;Line2&#xD;&#xA;Line3"/>

请注意,该值在文本中包含 。我知道这些是回车和换行的 XML 表示。

当我导入到 BeautifulSoup 时,值会转换为以下内容:

<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>

您会注意到 被转换为换行符。

我的用例要求该值保持原始值。知道如何让它留下来吗?或者将其转换回来?

源代码:

python :(2.7.11)

from bs4 import BeautifulSoup #version 4.4.0
s = BeautifulSoup(open('test.xml'),'lxml-xml',from_encoding="ansi")
print s.DIAttribute

#XML file looks like 
'''
<?xml version="1.0" encoding="UTF-8" ?>
<DIAttribute name="ObjectDesc" value="Line1&#xD;&#xA;Line2&#xD;&#xA;Line3"/>
'''

Notepad++ 说源 XML 文件的编码是 ANSI。

我尝试过的事情:

  • 我已经搜索了文档但没有成功。
  • 第 3 行的变体:

    print s.DIAttribute.prettify('ascii')
    print s.DIAttribute.prettify('windows-1252')
    print s.DIAttribute.prettify('ansi')
    print s.DIAttribute.prettify('utf-8')
    print s.DIAttribute['value'].replace('\r','&#xD;').replace('\n','&#xA;')  #This works, but it feels like a bandaid and will likely other problems will remain.
    

有什么想法吗?我感谢任何意见/建议。

最佳答案

仅作记录,首先是正确处理 实体的库:BeautifulSoup(data ,convertEntities=BeautifulSoup.HTML_ENTITIES)lxml.html.soupparser.unescapexml.sax.saxutils.unescape

这就是有效的(在 Python 2.x 中):

import sys
import HTMLParser

## accept file name as argument, or read stdin if nothing passed
data = len(sys.argv) > 1 and open(sys.argv[1]).read() or sys.stdin.read()

parser = HTMLParser.HTMLParser()
print parser.unescape(data)

关于python - 在 Python 中处理 `&#xA;`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856699/

相关文章:

c# - 数据库中存储的字符串的编码问题

python - 为什么这个正则表达式不起作用?

python - Django:对 (\d+) 的解释

encoding - 对 xhtml5 : no more `<?xml?>` and now mandatory `meta` ? 感到困惑

sql-server - 根据条件删除SQL Server中的XML节点

sql - 带有命名空间的 PostgresQL xpath

android - 从终端进程读取时出现 UnicodeDecodeError

python - 带有元数据的 HEIC 到 JPEG 转换

python - Scikit Learn - 决策树 - 每条记录结果的视觉表示

android - 对 Android CardView 的顶部部分进行颜色处理,同时保持圆角