刮片和字符串格式问题:一次使用“”刮片,另一次使用“”

2024-06-13 09:53:55 发布

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

此代码:

    url="http://www.royalcanin.fr/nos-aliments/gammes-pour-chiens/tous-les-aliments-pour-chiens/les-aliments-chez-les-veterinaires/chiens-en-bonne-sante/small/chien-sterilise/neutered-adult-small-dog"## read URL from an array coming from an Url-CSV
#print(url)

page_0=urllib.request.urlopen(url)
soup_0 = BeautifulSoup(page_0.read(),"html.parser") 
restricted_webpage_title_indication= soup_0.find( "div", {"class":"bloc"} ) # to get title and indication
readable_restricted_title_indication=str(restricted_webpage_title_indication)
soup_title_indication=BeautifulSoup(readable_restricted_title_indication,"html.parser")

indication=[]


for li in soup_title_indication.find_all('li'):
    indication.append(li.get_text().strip())

Pair_indication=["Indications",indication]
print(Pair_indication)

给了我以下打印:

['Indications', ['Risque de prise de poids', 'Sensibilité buccodentaire', "Risque de calculs d'oxalate et de struvite"]]

为什么最后一个元素与前两个元素一样用“”引用,而不是用“”引用? 我不明白的是,在这个网站上,三个“li”的标签和书写方式都是一样的。像这样:

  • 药品价格风险
  • 口腔癌敏感度
  • 草酸和鸟粪石结石风险
  • 为什么会这样?我错过了什么? 谢谢你的帮助


    Tags: fromanurlreadtitledelismall
    1条回答
    网友
    1楼 · 发布于 2024-06-13 09:53:55

    您没有遗漏任何内容,Python使用双引号打印了最后一个字符串,因为该字符串的主体已经有单引号,所以Python使用双引号打印该字符串,而不是使用单引号打印并显示内部单引号转义

    不管列表的所有元素是字符串,区别仅在打印期间

    这是一个非常简单的例子-

    >>> l = ['123','12\'3']
    >>> l
    ['123', "12'3"]
    >>> repr(l[1])
    '"12\'3"'
    >>> print(repr(l[1]))
    "12'3"
    

    请注意上面是repr()处理它的方式,当写入csv时,csv模块将以不同的方式正确处理它。示例-

    >>> l = ['123','12\'3',"222'333"]
    >>> with open('b.csv','w') as f:
    ...     writer = csv.writer(f,quotechar="'")
    ...     writer.writerow(l)
    ...
    24
    >>> with open('b.csv','r') as f:
    ...     reader = csv.reader(f,quotechar="'")
    ...     for line in reader:
    ...             print(line)
    ...
    ['123', "12'3", "222'333"]
    []
    

    csv文件看起来像-

    123,'12''3','222''333'
    

    相关问题 更多 >