试图写一个脚本,将返回我的国会选区多年来的选举结果。我已经编写了代码,可以提供最近的选举结果(2014年),当我运行代码时,它会以正确格式提供信息:
from bs4 import BeautifulSoup
from urllib.request import urlopen
# load the right wiki page [24th congress. district]
html = urlopen('https://en.wikipedia.org/wiki/New_York\'s_24th_congressional_district')
# make it soupy
soup = BeautifulSoup(html.read(), "lxml")
def electionResults(link):
biggross = soup.find('table',{'class':'wikitable'})
results2014 = biggross.find_next('table',{'class':'wikitable'})
results2014text = results2014.text
results2012 = results2014.find_next('table',{'class':'wikitable'})
results2012text = results2012.text
return results2014text
print(electionResults(soup))
输出如下所示:
US House election, 2014: New York District 24, 99.67% reporting
Party
Candidate
Votes
%
±%
Republican
John Katko
112,469
59.9
+16.6
Democratic
Dan Maffei
75,286
40.1
-7.6
Majority
37,183
19.8
+14.4
Turnout
187,755
100
-30.2
(根据柱子的长度,删去一些空格和新行。)
但是,当我将函数的最后一行更改为return results2014text,results2012text
时,会得到如下输出:
('\n\nUS House election, 2014: New York District 24, 99.67% reporting\n\n\nParty\nCandidate\nVotes\n%\n±%\n\n\n\nRepublican\nJohn Katko\n112,469\n59.9\n+16.6\n\n\n\nDemocratic\nDan Maffei\n75,286\n40.1\n-7.6\n\n\nMajority\n37,183\n19.8\n+14.4\n\n\nTurnout\n187,755\n100\n-30.2\n\n', 'US House election, 2012: New York District 24, 99% reporting\n\n\nParty\nCandidate\nVotes\n%\n±%\n\n\n\nDemocratic\nDan Maffei\n131,242\n48.7\n-1.1\n\n\n\nRepublican\nAnn Marie Buerkle\n116,641\n43.3\n-6.9\n\n\n\nGreen\nUrsula Rozum\n21,413\n8.0\n+8.0\n\n\nMajority\n14,601\n5.4\n+5.0\n\n\nTurnout\n269,296\n100\n+29.4')
当我将函数更改为返回多个选举结果时,如果只返回2014年的结果,如何保留函数返回的(相对)可行格式
返回多个值相当于返回一个元组
打印值时,它会打印str(值)。在元组上调用str时,对于元组中的项,不调用str(item),而是调用repr(item)。例如,这意味着字符串周围将有引号。在beautifulsoup的情况下,这会返回一些不太有用的东西
如果要保留格式,可以将元组中的每个项转换为字符串
return results2014text, results2012text
意味着您正在返回一个元组,要按您想要的方式打印元组,我们必须执行以下操作您试图同时返回两个变量,通过调用
return results2014text,results2012text
,Python获取这两个变量并创建一个由这两个变量组成的序列,很像一个列表。因此,当调用print(electionResults(soup))
时,打印的是元组对象,而不是字符串如果要打印这两个对象,请将print语句更改为:
相关问题 更多 >
编程相关推荐