在Python2.7中使用re.sub()从旧列表创建新列表

2024-03-29 11:21:40 发布

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

我的目标是获取一个XML文件,提取特定元素的所有实例,删除XML标记,然后处理剩余的文本

我从这个开始,它可以删除XML标记,但只能从整个XML文件中删除:

from urllib import urlopen
import re

url = [URL of XML FILE HERE]  #the url of the file to search

raw = urlopen(url).read()   #open the file and read it into variable

exp = re.compile(r'<.*?>')
text_only = exp.sub('',raw).strip()

我还有这个text2 = soup.find_all('quoted-block'),它创建了一个所有quoted-block元素的列表(是的,我知道我需要导入BeautifulSoup)

但我不知道如何将正则表达式应用到由soup.find\u all生成的列表。我试过使用text_only = [item for item in text2 if exp.sub('',item).strip()]和变体,但是我一直得到这个错误:TypeError: expected string or buffer

我做错什么了


Tags: 文件ofthetext标记importreurl