我在这里有一段代码来提取div.statement.p.Text

a = """<div class="theorem" id="theorem-AA" acro="AA" titletext="Adjoint of an Adjoint"> <h5 class="theorem"> <span class="type">Theorem </span><span class="acro">AA</span><span class="titletext"> Adjoint of an Adjoint</span> </h5> <div class="statement"><p>Suppose that $A$ is a matrix.  Then $\adjoint{\left(\adjoint{A}\right)}=A$.</p></div> <div class="proof"><a knowl="./knowls/proof.AA.knowl">Proof</a></div> </div><div class="context"><a href="http://linear.pugetsound.edu/html/section-MO.html#theorem-AA" class="context" title="Section MO">(in context)</a></div> """

from bs4 import BeautifulSoup as bs

soup = bs(repr(a),features = 'lxml')

statement = bs(repr(soup.find_all("div", {"class": "statement"})[0])).find('p').text

print(statement)

后来的yields 是

Suppose that $A$ is a matrix.  Then $\x07djoint{\\left(\x07djoint{A}\right)}=A$.

我需要输出为:

Suppose that $A$ is a matrix.  Then $\adjoint{\left(\adjoint{A}\right)}=A$.

我怎么能这样做呢?

推荐答案

问题出在你的字符串上,因为\abell character.

话虽如此,这基本上是将不可打印的字符引入到字符串文字中.

因此,要么用\\\进行转义,要么在字符串中添加r,然后按如下方式处理转义序列:

from bs4 import BeautifulSoup as bs

a = r"""<div class="theorem" id="theorem-AA" acro="AA" titletext="Adjoint of an Adjoint"> <h5 class="theorem"> <span class="type">Theorem </span><span class="acro">AA</span><span class="titletext"> Adjoint of an Adjoint</span> </h5> <div class="statement"><p>Suppose that $A$ is a matrix.  Then $\adjoint{\left(\adjoint{A}\right)}=A$.</p></div> <div class="proof"><a knowl="./knowls/proof.AA.knowl">Proof</a></div> </div><div class="context"><a href="http://linear.pugetsound.edu/html/section-MO.html#theorem-AA" class="context" title="Section MO">(in context)</a></div> """
soup = bs(repr(a), "html.parser")
statement = soup.find_all("div", {"class": "statement"})[0].find('p').getText()
print(bytes(statement, "utf-8").decode("unicode_escape"))

输出:

Suppose that $A$ is a matrix.  Then $\adjoint{\left(\adjoint{A}\right)}=A$.

Python相关问答推荐

产生镜像输出的MSG算法输出

使用Python从HTTP打印值

我可以使用极点优化这个面向cpu的pandas代码吗?

如何在telegram 机器人中发送音频?

Python中两个矩阵的自定义Hadamard风格产物

单击Python中的复选框后抓取数据

pyautogui.locateOnScreen在Linux上的工作方式有所不同

更改Seaborn条形图中的x轴日期时间限制

添加包含中具有任何值的其他列的计数的列

Pandas 在最近的日期合并,考虑到破产

max_of_three使用First_select、second_select、

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

对整个 pyramid 进行分组与对 pyramid 列子集进行分组

对于一个给定的数字,找出一个整数的最小和最大可能的和

按列分区,按另一列排序

Julia CSV for Python中的等效性Pandas index_col参数

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

如何更新pandas DataFrame上列标题的de值?

找到相对于列表索引的当前最大值列表""

在Admin中显示从ManyToMany通过模型的筛选结果