【问题标题】:How to write strings in different row and columns in a CSV (Python)如何在CSV(Python)中的不同行和列中写入字符串
【发布时间】:2017-01-09 01:38:41
【问题描述】:

我正在尝试从网站上抓取一些数据,我实际上可以获取它们,但它们是用 2 个不同的字符串编写的,看起来就像我的 .csv 中的那样:

aaa
bbb
ccc

和其他:

xxx
yyy
zzz

我想按照以下格式编写它们:

aaa | xxx
bbb | yyy
ccc | zzz

这是我目前写的代码:

# import libraries
import urllib2
from bs4 import BeautifulSoup
import csv  
i =0

# specify the url 
quote_page = 'http://www.alertepollens.org/gardens/garden/1/state/'

# query the website and return the html to the variable 'page'
response = urllib2.urlopen(quote_page)

# parse the html using beautiful soap and store in variable `soup`
soup = BeautifulSoup(response, 'html.parser')
test = soup
with open('allergene.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)

    pollene = (("".join(soup.strings)[65:]).encode('utf-8')).replace(' ','').replace('\n',' ').replace('    ',' ').replace('    ',' ').replace(' ','\n')
    print pollene

    state = (([img['alt'] for img in soup.find_all('img', alt=True)])).
    print state.encode
    polen = ''.join(pollene)
    for item in state:
        writer.writerow([item])
    for item2 in pollene:
        writer.writerow([item2])

主要问题之一是我有法语字符(é、ù、à 等)并且使用“strip()”不能正确显示这些字符。

你知道我该怎么做吗?

【问题讨论】:

  • 请显示生成这些 CSV 输出的代码。否则,如何提供帮助并不明显..
  • @alecxe: 刚刚添加 :)

标签: python string csv web-scraping beautifulsoup


【解决方案1】:
import csv
with open('a.csv') as a, open('x.csv') as x, open('out.csv', 'w', newline='') as out:
    a_lines = [line.strip()for line in a]
    x_lines = [line.strip()for line in x]
    rows = zip(a_lines, x_lines)
    writer = csv.writer(out, delimiter='|')
    writer.writerows(rows)

出来:

aaa|xxx
bbb|yyy
ccc|zzz

a.csv 是您的第一个 csv 文件,x.csv 是您的第二个 csv 文件,out.csv 是输出文件。

【讨论】:

  • 我想我并没有我想的那么清楚:/ |意思是在另一个单元格/列中我有一个文件,其中一个单元格(并且只有一个单元格)aaa bbb 和另一个:xxx yyy 相反,我想这样写:(第一行)aaa(第二列) xxx (new row) bbb (second colomn) yyy 不知道是否清楚,如果不是,我可以编辑我的问题:) 我的错 :/
猜你喜欢
  • 1970-01-01
  • 2022-12-05
  • 2019-05-01
  • 2020-08-20
  • 2011-10-18
  • 2019-03-01
  • 2017-06-17
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多