不久前,我为自己构建了这个小型 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('<(.*)>',i),'')
disc.extend([new_disc])
因此,在尝试删除一些垃圾文本的 new_disc 代码行之前,我通常会让我的文本看起来像这样
"Tailored DNA structures could find targeted cells and release their molecular payload selectively into the cells.<img src="http://feeds.feedburner.com/~r/sciencedaily/matter_energy/engineering/~4/J1bTggGxFOY" height="1" width="1" alt=""/>"
我想要的只是没有垃圾的文本,所以本质上只是:
"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('<(.*)>',i),'')
disc.extend([re.sub(r'<(.*)/>','',new_disc)])
关于用于查找的 Python 正则表达式和用于从列表中删除的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32775894/