2017-01-09 37 views
0

我試圖從網站中取出一些數據,我實際上可以得到它們,但是它們是用兩種不同的字符串寫成的,看起來像我的。 CSV:如何在CSV(Python)中寫入不同行和列中的字符串

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]) 

其中一個主要問題是,我有法語字符(E,U,A等),並使用「條()」不顯示這些字符正確。

你知道我該怎麼做嗎?

+4

請顯示產生這些CSV輸出的代碼。否則,這並不明顯如何提供幫助.. – alecxe

+0

@alecxe:剛添加它:) – Hawkydoky

回答

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是輸出文件。

+0

我想我並不像我想象的那麼清楚:/ the |意味着另一個細胞/ colomn 我在一個單元格(與只剩一格) AAA BBB 和另外一個已經一個文件: XXX YYY 相反,我想它這樣寫: (第一行)aaa(第二列)xxx (新行)bbb(第二列)yyy 不知道是否清楚,如果不是,我可以編輯我的問題:) 我的不好:/ – Hawkydoky

相關問題