为什么格式化在返回多个字符串时会变得很时髦?

时间:2015-11-03 20:20:54

标签: python beautifulsoup

尝试编写一个脚本,这些脚本将在我的国会选区多年来返回选举结果。我编写的代码将给我最新的选举结果(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年的结果时,我如何保留该函数吐出的(相对)可行的格式,以便返回多个选举的结果?

3 个答案:

答案 0 :(得分:1)

你试图通过调用return results2014text,results2012text一次返回两个变量,Python正在获取两个变量并创建两个变量的序列,就像列表一样。因此,当您调用print(electionResults(soup))时,您将打印一个元组对象,而不是字符串。

如果要打印两个对象,请将print语句更改为:

for results in electionResults(soup):
    print results

答案 1 :(得分:1)

返回多个值相当于返回一个元组。

打印值时,会打印str(值)。在元组上调用str时,不会调用元组str(item)中的项,而是调用repr(item)。例如,这意味着字符串将在它们周围有引号。在beautifulsoup的情况下,这会返回一些不太有用的东西。

如果要保留格式,可以将元组中的每个项目转换为字符串。

答案 2 :(得分:1)

return results2014text, results2012text表示你正在返回一个元组,并按照你想要的方式打印元组,我们要做类似的事情

result = electionResults(soup)
print result[0] + '\n' + result[1]