类似于这个问题,但我在实现代码时遇到了问题。
我有一个python程序,它从html文件中收集数据,包括书籍的重量、价格、书名等。我想将书籍分类为“n”个包,每个包不超过10磅。我可以运行程序没有错误,它提取的信息,但我没有得到任何结果包装。
这是我的代码,有人能给我建议吗?
import glob
from bs4 import BeautifulSoup
class weight():
def main():
data = []
for filename in glob.iglob('*.html'):
with open(filename) as f:
soup = BeautifulSoup(f)
weight = soup.find('b', text='Shipping Weight:').next_sibling
data.append({})
return weight
def Bin(weight):
def __init__(self):
self.items = []
self.sum = 0
def append(self, item):
self.items.append(item)
self.sum += item
def __str__(self):
return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items))
def pack(values, maxValue):
values = sorted(values, reverse=True)
bins = []
for item in values:
# Try to fit item into a bin
for bin in bins:
if bin.sum + item <= maxValue:
#print 'Adding', item, 'to', bin
bin.append(item)
break
else:
# item didn't fit into any bin, start a new bin
#print 'Making new bin for', item
Bin = weight()
bin.append(item)
bins.append(bin)
return bins
if __name__ == '__main__':
import random
def packAndShow(aList, maxValue):
print 'List with sum', sum(aList), 'requires at least', (sum(aList)+maxValue-1)/maxValue, 'bins'
bins = pack(aList, maxValue)
print 'Solution using', len(bins), 'bins:'
for bin in bins:
print bin
print
def pack(values, maxValue):
values = sorted(values, reverse=True)
bins = []
for item in values:
# Try to fit item into a bin
for bin in bins:
if bin.sum + item <= maxValue:
#print 'Adding', item, 'to', bin
bin.append(item)
break
else:
# item didn't fit into any bin, start a new bin
#print 'Making new bin for', item
Bin = weight()
bin.append(item)
bins.append(bin)
return bins
if __name__ == '__main__':
import random
def packAndShow(aList, maxValue):
print 'List with sum', sum(aList), 'requires at least', (sum(aList)+maxValue-1)/maxValue, 'bins'
bins = pack(aList, maxValue)
print 'Solution using', len(bins), 'bins:'
for bin in bins:
print bin
print
最佳答案
您定义了类,但代码的布局实际上从未运行过任何东西。
在之后移动所有内容
if __name__ == "__main__": #(the first one)
在这样的功能下:
def main():
paste the data from below
然后它会在调用时自动运行您的代码。
另外,我会认真研究重新调整代码的重点。想得更小更简单
你在那些可以优化和消除的东西上浪费了很多按键。比如定义一个append函数或者创建一个从未使用过的类函数。
我能给你的最好建议是尝试一些类似于this的方法来熟悉一些概念它将消除许多简单的错误,使调试更容易。