首页 > 解决方案 > 在 Python 中剥离列表中的字符串

问题描述

我在将元素插入循环时遇到问题...

import bs4

# Acces and read HTML file
exempleFile = open('betradar21.html', encoding="utf8")
soup = bs4.BeautifulSoup(exempleFile.read(), features="html.parser")

s = ["'tr', {'id': 'match-23206483'}", "'tr', {'id': 'match-23362461'}", "'tr', {'id': 'match- 
24358676'}", "'tr', {'id': 'match-21571325'}", "'tr', {'id': 'match-24325629'}", "'tr', {'id': 
'match-24352074'}", "'tr', {'id': 'match-24352106'}", "'tr', {'id': 'match-24352108'}", "'tr', {'id': 
'match-24352110'}", "'tr', {'id': 'match-24352112'}", "'tr', {'id': 'match-24423426'}", "'tr', {'id': 
'match-24423436'}"]


def dequote(s):
    '''
    If a string has single or double quotes around it, remove them.
    Make sure the pair of quotes match.
    If a matching pair of quotes is not found, return the string unchanged.
    '''
    if (s[0] == s[-1]) and s.startswith(("'", '"')):
        return s[1:-1]
    return s



for i, v in enumerate(s):
    dequote(v)
    print(v)
    print(soup.find_all(v))
    break

这将返回一个空列表,就像 v 是一个由 "" 包围的字符串。

print(soup.find_all("'tr', {'id': 'match-23206483'}"))

如果我在从双引号中删除它之后手动复制并粘贴 v 的值就可以了...

print(soup.find_all('tr', {'id': 'match-23206483'}))

像这样...

为什么 Python 会这样做,并且有一种方法可以“修复”这个问题?我想这与 {} 有关,但作为一个编程新手,我还找不到解释!

谢谢

标签: pythonstring

解决方案


让我们专注于较小的测试集

s = ["'tr', {'id': 'match-23206483'}"]

您看到的那些双引号不是字符串的一部分,它们只是 python 字符串文字中用于告诉解析器它应该从内容构建字符串的分隔符。在内部,该字符串是

'tr', {'id': 'match-23206483'}

它以 a 开头,以 a'结尾}dequote什么都不做,因为s[0]( ') 不等于s[-1]( })。因此,我们可以dequote摆脱等式并获得其余的代码。

for i, v in enumerate(s):
    print(v)
    print(soup.find_all(v))
    break

v是单个字符串。它看起来有点像参数列表,但实际上它只是一个字符串。如果它要成为您想要的参数,则需要以某种方式对其进行解析soup.find_all。事实上,v它看起来很像元组的 Python 文字。您可以让 python 评估字符串并为您构建元组。

>>> import ast
>>> ast.literal_eval("'tr', {'id': 'match-23206483'}")
('tr', {'id': 'match-23206483'})

好的。我们可以将数据转换为元组,并通过元组解包获得find_all.

import ast

for i, v in enumerate(s):
    print(v)
    params = ast.literal_eval(v)
    print(soup.find_all(*params))
    break

推荐阅读