我posted类似于这个问题,但我在实施代码方面遇到了麻烦。
我有一个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
答案 0 :(得分:0)
您定义了类,但代码的布局实际上从未运行任何内容。
在
后移动所有内容if __name__ == "__main__": #(the first one)
在它之类的函数之前:
def main():
paste the data from below
然后它会在调用它时自动运行您的代码。
另外,我会认真研究重新调整代码的方法。想想更小更简单 你可以在可以优化和消除的事情上浪费大量的击键。比如定义一个append函数或创建从未使用过的类函数。
我能给你的最好建议是尝试this之类的东西,以便更熟悉一些概念。它将消除许多简单错误并使调试更容易。