【问题标题】:Struggling with the formatting of scraped College football results与刮掉的大学橄榄球成绩的格式作斗争
【发布时间】:2019-11-17 22:28:36
【问题描述】:

这里是 Python 新手。我正在尝试格式化导入的大学橄榄球分数(来自梅西评级),以便我可以将它们导入 Excel。我需要创建一些标题 ["Date"、"Winner"、"Score"、"Loser"、"Score"] 并在列之间添加一些空间以提高可读性。据我所知,Pandas DataFrame 是要走的路。任何帮助将不胜感激。

到目前为止,这是我的代码:

import pandas as pd
from bs4 import BeautifulSoup
import urllib.request

address = 'https://www.masseyratings.com/scores.php?s=308075&sub=11604&dt=20191119'
response = urllib.request.urlopen(address)
html = response.read()

soup = BeautifulSoup(html,"html.parser")


table = soup.find("pre").get_text(strip=True)



print(table)

我得到的输出:

2019-11-16Southern Miss36 @UT San Antonio17           
2019-11-16 @Washington St49Stanford22           
2019-11-16TCU33 @Texas Tech31           
2019-11-16 @Temple29Tulane21           
2019-11-16Troy63 @Texas St27           
2019-11-16 @UAB37UTEP10           
2019-11-16 @Utah49UCLA3           
2019-11-16 @Utah St26Wyoming21           
2019-11-16 @Clemson52Wake Forest3           
2019-11-16 @Florida St49Alabama St12           
2019-11-16Virginia Tech45 @Georgia Tech0           
2019-11-16Ohio St56 @Rutgers21           
2019-11-16 @Iowa St23Texas21           
2019-11-16 @BYU42Idaho St10           
2019-11-19Ohio0 @Bowling Green0 Sch       
2019-11-19E Michigan0 @N Illinois0 Sch       

【问题讨论】:

  • 好的,很酷。所以你有一些代码和一些结果。 具体,结果有什么问题?你希望他们看起来像什么?请阅读How to Ask
  • 谢谢克里斯。我希望将数据格式化为表格格式,列之间有空格 - 类似于 Excel 工作表
  • “表”是什么意思?那如何映射到“所以我可以将它们导入 Excel”?您希望如何将每一行分成几列?
  • 是否可以在日期之后插入几个空格,获胜队,获胜队,失败队和失败队?这应该会提高可读性。
  • 是的,可以这样做。我首先将日期从每个字符串的前面剥离,因为它具有一致的长度和格式,然后分别处理后半部分。但是在输出中添加空格不会让您更接近导入 Excel。您的实际最终目标是什么?请阅读XY problem

标签: python pandas beautifulsoup


【解决方案1】:

字符串拆分可能是个好主意,但您可以对这个特定页面使用正则表达式模式来提取 4 列

import re, csv, requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.masseyratings.com/scores.php?s=308075&sub=11604&dt=20191119')
soup = bs(r.content, 'lxml')
p = re.compile(r'([^0-9-]+)\s{3,}')
p2 = re.compile(r'\s(\d+)\s')

with open("data.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
    w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
    w.writerow(['Date','Winner','Score1','Loser','Score2'])

    for line in soup.select_one('pre').text.split('\n')[:-4]:
        matches1 = p.findall(line)
        matches2 = p2.findall(line)
        row = [re.search(r'(\d{4}-\d{2}-\d{2})',line).group(0), matches1[0].strip(), matches2[0], matches1[1].strip(), matches2[1]]
        w.writerow(row)

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多