gpt4 book ai didi

python - 在 Python 中,如何从列表中删除包含某些类型字符的任何元素?

转载 作者:IT老高 更新时间:2023-10-28 20:51:45 25 4
gpt4 key购买 nike

抱歉,如果这是一个简单的问题,我对此仍然很陌生,但我花了一段时间寻找答案,但没有找到任何答案。我有一个看起来像这样可怕的困惑的列表:

['Organization name} ', '> (777) 777-7777} ', ' class="lsn-mB6 adr">1 Address, MA 02114 } ', ' class="lsn-serpListRadius lsn-fr">.2 Miles} MORE INFO YOUR LISTING MAP if (typeof(serps) !== \'undefined\') serps.arrArticleIds.push(\'4603114\'); ', 'Other organization} ', '> (555) 555-5555} ', ' class="lsn-mB6 adr">301 Address, MA 02121 } ', ' class="lsn-serpListRadius lsn-fr">.2 Miles} MORE INFO CLAIM YOUR LISTING MAP if (typeof(serps) !== \'undefined\') serps.arrArticleIds.push(\'4715945\'); ', 'Organization} ']

我需要处理它以便 HTML.py可以把里面的信息变成表格。出于某种原因,HTML.py 根本无法处理怪物元素(例如 'class="lsn-serpListRadius lsn-fr">.2 Miles} 更多信息如果 (typeof(serps) !==\' undefined\') serps.arrArticleIds.push(\'4603114\'); '等)。对我来说幸运的是,我实际上并不关心怪物元素中的信息,并且想要摆脱它们。

我尝试编写一个匹配所有超过两个字母的大写单词的正则表达式,以识别怪物元素,结果如下:

re.compile('[^a-z]*[A-Z][^a-z]*\w{3,}')

但我不知道如何将其应用于从列表中删除包含与该正则表达式匹配的元素。我该怎么做/这是正确的做法吗?

最佳答案

我认为您的正则表达式不正确,要匹配包含三个或更多字符的全大写单词的所有条目,您应该使用类似这样的内容 re.search:

regex = re.compile(r'\b[A-Z]{3,}\b')

您可以使用列表理解或 filter 内置函数进行过滤:

full = ['Organization name} ', '> (777) 777-7777} ', ' class="lsn-mB6 adr">1 Address, MA 02114 } ', ' class="lsn-serpListRadius lsn-fr">.2 Miles} MORE INFO YOUR LISTING MAP if (typeof(serps) !== \'undefined\') serps.arrArticleIds.push(\'4603114\'); ', 'Other organization} ', '> (555) 555-5555} ', ' class="lsn-mB6 adr">301 Address, MA 02121 } ', ' class="lsn-serpListRadius lsn-fr">.2 Miles} MORE INFO CLAIM YOUR LISTING MAP if (typeof(serps) !== \'undefined\') serps.arrArticleIds.push(\'4715945\'); ', 'Organization} ']
regex = re.compile(r'\b[A-Z]{3,}\b')
# use only one of the following lines, whichever you prefer
filtered = filter(lambda i: not regex.search(i), full)
filtered = [i for i in full if not regex.search(i)]

以下列表中的结果(我认为这是您正在寻找的:

>>> pprint.pprint(filtered)
['Organization name} ',
'> (777) 777-7777} ',
' class="lsn-mB6 adr">1 Address, MA 02114 } ',
'Other organization} ',
'> (555) 555-5555} ',
' class="lsn-mB6 adr">301 Address, MA 02121 } ',
'Organization} ']

关于python - 在 Python 中,如何从列表中删除包含某些类型字符的任何元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7014674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com