用于查找的 Python 正则表达式和用于从列表中删除的正则表达式

标签 python regex

不久前,我为自己构建了这个小型 RSS 阅读器,并受到启发来更新它,以排除描述标签中的垃圾内容。我现在正忙着测试它以删除 &'lt; (全部内容)>>从描述标签来看,我在进行这个仪式时遇到了困难。

到目前为止我的代码看起来像这样

from re import findall
from Tkinter import *
from urllib import urlopen

disc = []
URL = 'http://feeds.sciencedaily.com/sciencedaily/matter_energy/engineering?format=xml'
O_W = urlopen(URL).read()

disc_ex = findall('<description>(.*)</description>',O_W)
for i in disc_ex:
    new_disc = i.replace(findall('&lt;(.*)&gt;',i),'')
    disc.extend([new_disc])

因此,在尝试删除一些垃圾文本的 new_disc 代码行之前,我通常会让我的文本看起来像这样

"Tailored DNA structures could find targeted cells and release their molecular payload selectively into the cells.&lt;img src="http://feeds.feedburner.com/~r/sciencedaily/matter_energy/engineering/~4/J1bTggGxFOY" height="1" width="1" alt=""/&gt;"

我想要的只是没有垃圾的文本,所以本质上只是:

"Tailored DNA structures could find targeted cells and release their molecular payload selectively into the cells."

对我有什么建议吗?

最佳答案

有多种解决方案,例如 BeautifulSoup。要遵循您的想法,请避免使用 '<' ...'>' 括号内的字符串,只需更改最后一行:

...
for i in disc_ex:
    new_disc = i.replace(findall('&lt;(.*)&gt;',i),'')
    disc.extend([re.sub(r'<(.*)/>','',new_disc)])

关于用于查找的 Python 正则表达式和用于从列表中删除的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32775894/

相关文章:

c++ - boost 正则表达式排除一个字符

python - 是否有单一的匹配和替换功能?

python - 用于语法突出显示的 powerpoint/openoffice 插件

python - Scipy 基于误差平方和优化常数

python - 为什么 TLS 很慢?

java - 小数点前 6 位和小数点后 2 位的正则表达式

python - 替换缩写列表中的点?

python - 将字典转换为 Python 可读的内容

python - Django 中的 Web 服务

regex - 删除大文件中的注释