【问题标题】:How to Solve Syntax Error in Python with DataFrame?如何使用 DataFrame 解决 Python 中的语法错误?
【发布时间】:2023-02-07 03:45:16
【问题描述】:

我正在学习网络抓取,但在尝试创建带有数据框的表时遇到了问题。

这是我的代码:

import requests
from bs4 import BeautifulSoup
import re
import pandas as pd

url = 'https://webscraper.io/test-sites/e-commerce/allinone/phones/touch'
page = requests.get(url) 

product_name = soup.find_all('a', class_ = 'title')
price = soup.find_all('h4', class_ = 'pull-right price')
reviews = soup.find_all('p', class_ = 'pull-right')
description = soup.find_all('p', class_ = 'description')

product_name_list = []
for i in product_name:
    names = i.text
    print(product_name_list.append(names))
    
price_list = []
for i in price:
    prices = i.text
    print(price_list.append(prices))
    
review_list = []
for i in reviews:
    review = i.text
    print(review_list.append(review))
    
description_list = []
for i in description:
    descriptions = i.text
    print(description_list.append(descriptions))

# create a table with labels and call the empty list to the table variable
table = pd.DataFrame{('Product Name':product_name_list, 'Description':description_list,
                     'Price':price_list,'Reviews':review_list)}
print(table)

输出:

line 83
    table = pd.DataFrame{('Product Name':product_name_list, 'Description':description_list,
                        ^
SyntaxError: invalid syntax

知道如何解决这个问题吗?

创建一个表,其中包含“产品名称”、“评论”、“价格”和“描述”的数据列表。

【问题讨论】:

  • 把圆括号和方括号按正确的顺序放好??
  • 修复语法。这不是您在运行时处理的事情。这是一个需要在源代码中更正的错误。您已将用于进行函数调用的括号与用于定义要用作参数的字典的大括号交换。
  • 如果这不是您需要修复的简单拼写错误,您需要花更多时间与the tutorial 一起学习正确的 Python 语法。
  • 您的 cmets 没有帮助。提问者已经知道存在语法错误,问题是寻求帮助来识别它。
  • 感谢大家的帮助。我根据你的 cmets 修复了它。我是一个介绍性的 python 课程,我的项目是网络抓取。我只是没有记住正确的 Python 语法。

标签: python web-scraping


【解决方案1】:

看起来您正在尝试将字典作为参数传递给函数:

table = pd.DataFrame{('Product Name':product_name_list, 'Description':description_list,
                     'Price':price_list,'Reviews':review_list)}

如果你用两行来做,它会更清楚哪里出了问题:

# create the dictionary
arg = {'Product Name':product_name_list, 'Description':description_list,
                     'Price':price_list,'Reviews':review_list}

# pass the dictionary as the argument
table = pd.DataFrame(arg)

内联:

table = pd.DataFrame({'Product Name':product_name_list, 'Description':description_list,
                     'Price':price_list,'Reviews':review_list})

感谢@thierry-lathuille 的详细回复:pd.DataFrame 的签名

【讨论】:

  • 看起来您不知道pd.DataFrame 及其接受的参数。请阅读the relevant documentation
  • @ThierryLathuille 我特别指出,这只解决了这个问题范围内的SyntaxError,并没有解决无效参数。
  • 正如@chepner 和我自己在第一个 cmets 中所解释的那样,语法错误是圆括号和大括号被交换了。就这样。建议使用关键字参数而不是 dict 是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
相关资源
最近更新 更多