我编写了一个脚本,该脚本从德克萨斯州执行的违规者处获取html表(由于限制而无法发布链接,但可以在getcsv.py的代码中找到)并将其转换为csv文件。然后另一个剧本计算每个人的比赛。然而,我一直有一个问题,除了白人和西班牙裔之外的其他所有人,然后分开计算。这: [('White', 237), ('Black', 196), ('Hispanic', 100), ('Other', 2), ('White ', 1), ('Hispanic ', 1)]
就是结果。
这是下载csv文件(getcsv.py)
的脚本import csv
from bs4 import BeautifulSoup
from urllib.request import urlopen
soup = BeautifulSoup(urlopen('http://www.tdcj.state.tx.us/death_row/dr_executed_offenders.html'), "html.parser")
table = soup.find('table')
headers = [header.text for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text for val in row.find_all('td')])
with open('new.csv', 'w', encoding="utf8", newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(row for row in rows if row)
这是参加比赛的脚本(analyse.py)
import csv
import collections
race = collections.Counter()
with open('new.csv') as input_file:
next(input_file)
for row in csv.reader(input_file, delimiter=','):
race[row[8]] += 1
list(race)
racecom = race.most_common()
print ('Number of white people executed: %s' % grades['White'])
print ('Number of black people executed: %s' % grades['Black'])
print ('Number of Hispanic people executed: %s' % grades['Hispanic'])
print ('Number of Other people executed: %s' % grades['Other'])
print (racecom)
然而,当我使用convertcsv.org生成的csv文件时,问题就消失了,所以我很确定它的getcsv.py是否有错误。
生成的文件可以在https://www.dropbox.com/s/gz0kob2miejqucq/actual.csv?dl=0下载为actual.csv,自动下载的文件可以在https://www.dropbox.com/s/chkycm21konvcw0/new.csv?dl=0找到new.csv。
提前致谢。
答案 0 :(得分:2)
空白很重要。如果键应该相同,你必须将它们剥离:
with open('new.csv') as input_file:
next(input_file)
race = collections.Counter(row[8].strip()
for row in csv.reader(input_file, delimiter=','))