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