2015-10-15 94 views
-1

首先想的說,我一直在研究論壇上約2天,並沒有發現任何適合我。那麼,我們走吧。我廢除一個網站,我只需要按順序設置python代碼的輸出。Python,代碼爲csv。故障

這就是我它運行後得到:

1 
Kidderminster Harr 
1183 
283 
138 
170 
1005 
731 
"" 
208 
148 
236 
813 
877 
"" 
+210 
1727 
.536 

在單列..

這就是我想要的東西:我想是這樣

1, Kidderminster Harr, 1183, 283, 138, 170, 1005, 731, "", 208, 148, 236,etc... 

一個CSV前一段時間,我記得加+「」每個元素將使招......現在我不知道爲什麼不工作了..

這是我到目前爲止:

import requests 
from bs4 import BeautifulSoup 

req = requests.get('http://www.statto.com/football/stats/england/national-league/all-time-table', headers={'User-Agent':'a-user-agent'}) 
soup = BeautifulSoup(req.text) 
summary = soup.find("div",{"id" : "page-content"}) 
tables = summary.find('table') 
count = 0 
for row in tables.findAll('tr'): 
    for cell in row.findAll('td'): 
     data = cell.getText() 
     if (count < 18): 
      data = data + ';' 
      print data 
     count += 1 
     if (count==19): 
      print data 
     count = 0 

任何想法將非常感激。

回答

0
print data 

打印數據和換行符。

print data, 

壓制換行符。 這有幫助嗎?

我想你想:

if (count < 18): 
    data = data + "," 
    print data, 
    count += 1 
elif (count==19): 
    print data 
    count = 0 

有更Python的方式來做到這一點,但是這是回答你的問題,我認爲。

+0

這就是我講的!謝啦!!我已經3天瘋了,只是我忘了把這個','打印後! – Enaggi

+0

Python 3和/或「from __future__ import print_function」爲您提供打印函數與打印語句。這可以傳遞一個「end」參數,如end =「」來抑制換行符。但在Python 2中,這是它的工作原理。 – RobertB

0

如果我理解正確的話,你想拆的空白,然後用逗號連接:

>>> string = "1 Kidderminster Harr 1183 283 138 170 1005 731 "" 208 148 236 813 877 "" +210 1727 .536" 
>>> ", ".join(string.split()) 
'1, Kidderminster, Harr, 1183, 283, 138, 170, 1005, 731, 208, 148, 236, 813, 877, +210, 1727, .536' 

split方法將字符串分割成其空白列表,然後join創建一個字符串每個列表成員用", "分隔。

編輯:你的問題已經改變了一點,但如果你能列的每個部分追加到一個列表,然後調用join

0

看你的代碼,你首先需要初始化結果字符串,像這樣:

result = "" 

做第二個for循環之前。那麼你需要添加到循環在打印數據變量兩個地

result = result + data + ", " 

result = result + data 

,然後是第二行之後

print result 

你應該得到你需要什麼。