python - 从网络抓取的出生姓名数据中确定最常见的名字
问题描述
我的任务是从这个页面https://www.ssa.gov/cgi-bin/popularnames.cgi进行网络抓取。在那里,您可以找到最常见的出生名称列表。现在我必须找到给定年份女孩和男孩最常用的名字(换句话说,两种性别都使用完全相同的名字),但我不知道我是怎么做到的。使用下面的代码,我解决了上一个任务以输出给定年份的列表,但我不知道如何修改我的代码,所以我得到了女孩和男孩最常见的名字。
import requests
import lxml.html as lh
url = 'https://www.ssa.gov/cgi-bin/popularnames.cgi'
string = input("Year: ")
r = requests.post(url, data=dict(year=string, top="1000", number="n" ))
doc = lh.fromstring(r.content)
tr_elements = doc.xpath('//table[2]//td[2]//tr')
cols = []
for col in tr_elements[0]:
name = col.text_content()
number = col.text_content()
cols.append((number, []))
count=0
for row in tr_elements[1:]:
i = 0
for col in row:
val = col.text_content()
cols[i][1].append(val)
i += 1
if(count<4):
print(val, end = ' ')
count += 1
else:
count=0
print(val)
解决方案
这是一种方法。第一步是按名称对数据进行分组,并记录有多少性别使用了该名称及其总数。之后,我们可以使用具有多个性别的名称过滤结构。最后,我们按计数对这个多性别列表进行排序并取第 0 个元素。这是我们今年最受欢迎的多性别名称。
import requests
import lxml.html as lh
url = "https://www.ssa.gov/cgi-bin/popularnames.cgi"
year = input("Year: ")
response = requests.post(url, data=dict(year=year, top="1000", number="n"))
doc = lh.fromstring(response.content)
tr_elements = doc.xpath("//table[2]//td[2]//tr")
column_names = [col.text_content() for col in tr_elements[0]]
names = {}
most_common_shared_names_by_year = {}
for row in tr_elements[1:-1]:
row = [cell.text_content() for cell in row]
for i, gender in ((1, "male"), (3, "female")):
if row[i] not in names:
names[row[i]] = {"count": 0, "genders": set()}
names[row[i]]["count"] += int(row[i+1].replace(",", ""))
names[row[i]]["genders"].add(gender)
shared_names = [
(name, data) for name, data in names.items() if len(data["genders"]) > 1
]
most_common_shared_names = sorted(shared_names, key=lambda x: -x[1]["count"])
print("%s => %s" % most_common_shared_names[0])
如果您好奇,以下是自 2000 年以来的结果:
2000 => Tyler, 22187
2001 => Tyler, 19842
2002 => Tyler, 18788
2003 => Ryan, 20171
2004 => Madison, 20829
2005 => Ryan, 18661
2006 => Ryan, 17116
2007 => Jayden, 17287
2008 => Jayden, 19040
2009 => Jayden, 19053
2010 => Jayden, 18641
2011 => Jayden, 18064
2012 => Jayden, 16952
2013 => Jayden, 15462
2014 => Logan, 14478
2015 => Logan, 13753
2016 => Logan, 12099
2017 => Logan, 15117
推荐阅读
- android - Android 架构组件
- php - ( laravel - Php ) 我想要一个显示数据库中总用户数的代码
- spring - @RefreshScope 副作用 - 自动配置、自动连接
- angular - 在角度日历视图中获取日期范围
- oracle - 忽略空间的Oracle唯一约束和唯一索引
- for-loop - 使用 for 循环返回 pyspark 数据帧的问题
- kubernetes - k8s scdf2如何在任务中配置volumenMount(无自由文本)
- spring - 使用 Feign 将数据文件上传为字节数组
- angular - 属性名称和功能复合
- sling - 如何通过 Sightly/HTL 中的节点 UUID 访问资源?