python从混合代码中选择文本

2024-07-02 11:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

目前更新:

美丽之声部分起作用。如何删除<style><\style>之间的任何文本?你知道吗


我正试图写一个函数,以便从这样一个文本

<style>.card {
 font-family: arial;
 font-size: 20px;
 text-align: center;
 color: black;
 background-color: white;
}
</style>qüestion

<hr id=answer>

änswer

只把这些拿出来

word[0] = qüestion
word[1] = änswer

这些词可能包含元音变调。你知道吗

我原以为reregex可以胜任这项工作,但我没能成功!感谢您的帮助:)


Tags: 函数text文本sizestylecardfamilyword
1条回答
网友
1楼 · 发布于 2024-07-02 11:35:15

How to remove whatever text between <style> and </style>?

您需要^{}标记style^{}它们:

>>> from bs4 import BeautifulSoup
>>> s = '''<style>.card {
 font-family: arial;
 font-size: 20px;
 text-align: center;
 color: black;
 background-color: white;
}
</style>question

<hr id=answer>

answer'''
>>> soup = BeautifulSoup(s, "html.parser")
>>> styles = [style.extract() for style in soup('style')] # Or, you may use...
>>> # soup.find("style").clear()
>>> results = soup.text.strip().split()
>>> print(results)
[u'question', u'answer']

使用[style.extract() for style in soup('style')],您将获得所有带有内部HTML的style标记,并将它们从soup中删除。然后,它的text属性只包含用一些空格分隔的questionanswer,所以您所需要做的就是拆分字符串。你知道吗

相关问题 更多 >