【问题标题】:Write a list and strings in one row each in its own cell在一行中写一个列表和字符串,每个在自己的单元格中
【发布时间】:2017-11-25 17:52:54
【问题描述】:

我提取了四个项目(一个字符串列表和三个字符串),我想将所有四个项目写在一行中。我认为这是可能的,只需要一点帮助。

r_ingredients_wtht_tags = []
    for link in r_links:
        r = requests.get(link)
        # print(r.status_code)
        if r.status_code == requests.codes.ok:
            soup = BeautifulSoup(r.content, "html.parser")
            r_name = soup.find('h1', {'itemprop': 'name'}).text.replace('recipe', '')
            r_prep_time = soup.select('li.recipe-meta-tag')[1].text
            r_ingrdnts_with_tags = soup.select('span[itemprop="ingredients"]')

            for r_ingrdnts in r_ingrdnts_with_tags:  # Remove span tags from list items
                r_ingredients_wtht_tags.append(r_ingrdnts.text)
            # print(r_ingredients_wtht_tags)
            # exit()
            r_image_src = soup.find('img', {'itemprop': 'image'}).get('src')
            r_image_url = 'https://website.com' + r_image_src # dummy website
            r_url = link

            # Download the recipe image
            print('Downloading image %s...' % (r_image_url))
            rec_image = requests.get(r_image_url)
            rec_image.raise_for_status()  # Will raise an exception if above request failed.

            # Create image folder to store current recipe image
            os.makedirs('recipe' + str(image_fold_count), exist_ok=True)

            # Save recipe image
            imageFile = open(os.path.join('recipe' + str(image_fold_count), os.path.basename(r_image_url)), 'wb')
            for chunk in rec_image.iter_content(100000):
                imageFile.write(chunk)
            imageFile.close()

            # write to csv file. NOTE TO SELF: MOVE THIS TO ITS OWN FUNCTION
            fileWriter.writerow(zip(r_name, r_prep_time, r_ingredients_wtht_tags, r_url +"\n"))

            image_fold_count += 1  # Increment recipe folder counter

【问题讨论】:

  • “为什么这段代码不工作”的密切原因在这里完美适用,所以我将在问题结束之前引用它:“寻求调试帮助的问题(“为什么不是这个代码工作?") 必须包含所需的行为、特定问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。"
  • 使用按钮{} 正确格式化代码。
  • 为什么用zip()写csv?你应该使用列表[r_name, r_prep_time, r_ingredients_wtht_tags, r_url +"\n"]
  • 为什么要把"\n" 加到r_url 上? csv 将在行尾自动添加\n
  • 如果r_ingredients_wtht_tags 是一个列表,并且您想要分隔单元格中的所有元素然后以这种方式创建列表[r_name, r_prep_time] + r_ingredients_wtht_tags + [r_url]

标签: python python-3.x csv beautifulsoup


【解决方案1】:

如果r_ingredients_wtht_tags 是一个列表,并且您希望所有四个元素在一行中但在单独的单元格中,那么您可以通过这种方式创建列表

row = [r_name, r_prep_time, r_ingredients_wtht_tags, r_url]

或将r_ingredients_wtht_tags 转换为带有一些分隔符的字符串。
您可以使用事件,csv 将其自动放入" "

ingredients = ",".join(r_ingredients_wtht_tags)
row = [r_name, r_prep_time, ingredients, r_url]

如果每种成分都必须在单独的单元格中,您可以这样做

row = [r_name, r_prep_time] + r_ingredients_wtht_tags + [r_url]

并在csv 中写入,不带zip()(不带"\n" - csv 将在行尾添加)

fileWriter.writerow(row)   

【讨论】:

  • 嗨@furas。谢谢你的帮助。我能够在一行中写入,但第一个列表对 csv 中的所有行重复。我想看看它是否是我的代码逻辑,即使编写器对象在 for 循环中。
  • 使用print()来显示变量以及执行了哪部分代码。它有助于发现问题。
  • 修复了重复的问题。我已经在循环外声明了空列表。傻我。谢谢你的帮助。你上面的修复工作。
  • 旁注:在 windows 上,在创建 writer 对象时将 newline='' 传递给 open 函数会删除在每行之后添加到 csv 文件中的新行。
  • 刚刚尝试为您的有用答案投票,但我不能,因为我还是这里的新手。非常感谢。
猜你喜欢
  • 2015-02-15
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2022-10-01
  • 1970-01-01
相关资源
最近更新 更多