gpt4 book ai didi

python - 从网络抓取的出生姓名数据中确定最常见的姓名

转载 作者:行者123 更新时间:2023-12-01 07:04:08 25 4
gpt4 key购买 nike

我的任务是从此页面 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

关于python - 从网络抓取的出生姓名数据中确定最常见的姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com