Skip to main content
 首页 » 编程设计

Python:从列表中删除/过滤等号

2024年10月01日6linjiqin

快速提问,因为我被卡住了,似乎无法再进一步了。

这是我的问题:

我在一个数据集中工作,我从 XML 转储中提取维基百科页面的每个部分名称。我从文本中提取文本,每个部分都通过以下方式给出:

==栏目名称==

不过,也有我不想处理的小节,通过

===栏目名称===

目前我正在使用正则表达式从文本 (pagetext) 中过滤部分

sections = re.findall("==(.*)==", pagetext) 

然而,结果是小节也包含在我的节列表中。问题:如何从我的章节列表中过滤这些小节,以便仅从文本中检索章节。

我已经使用了这个列表推导式但是它不起作用

sections = [section for section in sections if section[0] == (r"^=")] 

非常感谢任何帮助:) 非常感谢!!

请您参考如下方法:

如果周围的文本完全是任意的,您可能不得不求助于 negative lookahead and negative lookbehind :

re.findall(r'(?<!=)==(?!=)(.*?)(?<!=)==(?!=)', pagetext) 
# (?<!...) only matches if not preceded by ... 
# (?!...) only matches if not followed by ... 
# (.*?) the captured group itself, anything matched non-greedily 

这确保包含 '==' 的部分之前或之后都没有 '='。