2014-12-02 669 views
1

我對Python相當陌生,而且我寫了一個刮板來打印數據,我放棄了我需要的確切方式,但是我無法將數據寫入文件。我需要它看起來完全相同的方式,並以相同的順序,因爲它確實當它在空閒Python:將多個變量寫入文件

import requests 
import re 
from bs4 import BeautifulSoup 

year_entry = raw_input("Enter year: ") 

week_entry = raw_input("Enter week number: ") 

week_link = requests.get("http://sports.yahoo.com/nfl/scoreboard/?week=" + week_entry + "&phase=2&season=" + year_entry) 

page_content = BeautifulSoup(week_link.content) 

a_links = page_content.find_all('tr', {'class': 'game link'}) 

for link in a_links: 
     r = 'http://www.sports.yahoo.com' + str(link.attrs['data-url']) 
     r_get = requests.get(r) 
     soup = BeautifulSoup(r_get.content) 
     stats = soup.find_all("td", {'class':'stat-value'}) 
     teams = soup.find_all("th", {'class':'stat-value'}) 
     scores = soup.find_all('dd', {"class": 'score'}) 

     try: 
       game_score = scores[-1] 
       game_score = game_score.text 
       x = game_score.split(" ") 
       away_score = x[1] 
       home_score = x[4] 
       home_team = teams[1] 
       away_team = teams[0] 
       away_team_stats = stats[0::2] 
       home_team_stats = stats[1::2] 
       print away_team.text + ',' + away_score + ',', 
       for stats in away_team_stats: 
         print stats.text + ',', 
       print '\n' 
       print home_team.text + ',' + home_score +',', 
       for stats in home_team_stats: 
         print stats.text + ',', 
       print '\n' 

     except: 
       pass 

打印我是如何得到這個完全糊塗了打印到一個txt文件,它打印相同的方式在IDLE中。該代碼只能在NFL賽季完成的幾周內運行。所以,如果你測試代碼,我建議一年= 2014星期= 12(或之前)

感謝,

JT

回答

1

寫信給你需要建立行作爲字符串文件,然後將該行寫入文件。

你會使用這樣的:

# Open/create a file for your output 
with open('my_output_file.csv', 'wb') as csv_out: 
    ... 
    # Your BeautifulSoup code and parsing goes here 
    ... 
    # Then build up your output strings 
    for link in a_links: 
     away_line = ",".join([away_team.text, away_score]) 
     for stats in away_team_stats: 
      away_line += [stats.text] 
     home_line = ",".join(home_team.text, home_score]) 
     for stats in home_team_stats: 
       home_line += [stats.text] 

     # Write your output strings to the file 
     csv_out.write(away_line + '\n') 
     csv_out.write(home_line + '\n') 

這是一個快速和骯髒的修復。要正確地做到這一點,你可能想看看csv模塊(docs

0

從你的輸出結構,我同意傑米使用CSV是一個合理的選擇。

但是由於您使用的是Python 2,因此可能使用來使用打印語句的替代形式打印到文件。

https://docs.python.org/2/reference/simple_stmts.html#the-print-statement

打印也具有延長的形式中,通過上述 語法的第二部分限定。這種形式有時被稱爲「print chevron」。在此形式中,>>必須 之後的第一個表達式評估爲「類文件」對象,特別是具有上述write()方法的對象。通過這種擴展形式, 後續表達式被打印到這個文件對象。如果第一個 表達式的計算結果爲None,則將sys.stdout用作 輸出的文件。

例如,

outfile = open("myfile.txt", "w") 
print >>outfile, "Hello, world" 
outfile.close() 

然而,這個語法是不是在Python 3的支持,所以我想它可能不是使用它是一個好主意。 :) FWIW,除了我傾向於使用print >>sys.stderr作爲錯誤消息之外,我通常在寫入文件時在我的代碼中使用write()方法。