【问题标题】:Python: Writing multiple variables to a filePython:将多个变量写入文件
【发布时间】:2014-12-02 10:03:48
【问题描述】:

我对 Python 还很陌生,我已经编写了一个刮板,它可以按照我需要的确切方式打印我刮掉的数据,但是我在将数据写入文件时遇到了麻烦。我需要它看起来与在 IDLE 中打印时完全相同的方式和顺序

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 赛季结束的几周内运行。因此,如果您测试代码,我建议 year = 2014 和 week = 12(或之前)

谢谢,

JT

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案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)

    【讨论】:

      【解决方案2】:

      从您的输出结构来看,我同意 Jamie 的观点,即使用 CSV 是一个合乎逻辑的选择。

      但由于您使用的是 Python 2,因此可以使用另一种形式的 print 语句来打印到文件。

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

      print 还有一个扩展形式,由 上面描述的语法。这种形式有时被称为“打印 雪佛龙。”在这种形式中,>> 之后的第一个表达式必须 评估为“类文件”对象,特别是具有 如上所述的 write() 方法。通过这种扩展形式, 随后的表达式将打印到此文件对象。如果第一个 表达式的计算结果为无,然后 sys.stdout 用作文件 输出。

      例如,

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

      但是,Python 3 不支持这种语法,所以我想使用它可能不是一个好主意。 :) FWIW,我通常在写入文件时在我的代码中使用 file write() 方法,除了我倾向于使用print >>sys.stderr 来获取错误消息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        • 2018-01-01
        • 1970-01-01
        • 2012-11-02
        • 1970-01-01
        • 2023-01-25
        相关资源
        最近更新 更多