2016-05-31 67 views
1

我正在写一个脚本来计算某些特定单词并给出了单词的具体计数。如何在python中的类中打印'%d'和'%s'

我目前卡在打印数据,从类。

我的下一个任务是将这些值放入一个使用数据驱动框架的excel文件中。

这是我现在为止已完成:

a = driver.page_source 
soup = BeautifulSoup(a, "html.parser") 


class counter_class: 
    def count(self, tittle, block_code): 
     blockcode_passed = block_code.count("Passed") 
     blockcode_blocked = block_code.count("Blocked") 
     blockcode_fail = block_code.count("Failed") 
     blockcode_retest = block_code.count("Retest") 
     blockcode_cannot_test = block_code.count("Connot Test") 
     blockcode_completed = block_code.count("Completed") 
     blockcode_passwc = block_code.count("Pass With Concern") 
     blockcode_untested = block_code.count("Untested") 

     print '%s' + ' ' + '%d' %(tittle,blockcode_passed) 
     print '%s' + ' ' + '%d' %(tittle,blockcode_fail) 
     print "Apps Gateway(Untested)" + ' ' + '%d' %(blockcode_untested) 
     print "Apps Gateway(Blocked)" + ' ' + '%d' %(blockcode_blocked) 
     print "Apps Gateway(Retest)" + ' ' + '%d' %(blockcode_retest) 
     print "Apps Gateway(Cannot Test)" + ' ' + '%d' %(blockcode_cannot_test) 
     print "Apps Gateway(Completed)" + ' ' + '%d' %(blockcode_completed) 
     print "Apps Gateway(Pass With Concern)" + ' ' + '%d' %(blockcode_passwc) 




apps_gateway = soup.find_all("div", {"id":"group-3191427"}) 
apps_gateway_str = str(apps_gateway) 
apps_gateway_obj=counter_class() 
apps_gateway_obj.count("appsgateway",apps_gateway_str) 

代码作品,但代码的第一部分的第二部分:

print '%s' + ' ' + '%d' %(tittle,blockcode_passed) 
print '%s' + ' ' + '%d' %(tittle,blockcode_fail) 

给我的错误:

print '%s' + ' ' + '%d' %(tittle,blockcode_passed) 
TypeError: %d format: a number is required, not str 

回答

1

还有在操作顺序的问题。实际执行的是:print '%s' + ' ' + ('%d' %(tittle,blockcode_passed))

Python正在尝试使用tittle来代替%d参数。你可以改变它:

print ('%s' + ' ' + '%d') %(tittle,blockcode_passed) 
# or 
print "%s %d" %(tittle,blockcode_passed) 
+0

这做了我的工作。 –

0

您正在使用%运算符将格式应用于最后一个字符串,在此情况下为'%d'。这不适用于title的说法。

0

您可以从格式字符串中删除字符串连接开始:'%s' + ' ' + '%d' - >'%s %d'。用你的语法的问题是,该字符串格式化你的情况首先进行的级联发生之前,所以:

'%s' + ' ' + '%d' % ('s', 2) 

蟒蛇尝试与你给它的元组的第一个元素,这是一种替代%d字符串,给你错误TypeError: %d format: a number is required, not str

0

谨防运算符优先级

'%s' + ' ' + '%d' %(tittle,blockcode_passed) 

意味着

'%s' + ' ' + ('%d' %(tittle,blockcode_passed))