我使用Python的pattern.web模块执行一些基本的Web挖掘任务。我正在尝试仅提取前15个关键字,并用逗号附加每个关键字","
。所以,我最终的文件包含看起来像一个关键字列表:DOM解析文档:根据条件添加和删除逗号
scallops, scallop shells, sea scallops, scallop shell, how to cook scallops, scallop shells for sale, frozen scallops, fresh scallops, dry scallops, cooking scallops, baptism shell, scallop recipe, large scallop shells, diver scallops, bay scallops,
现在,我不希望逗号","
15日/最后一个关键字后"bay scallops,"
我需要一点点的帮助下修改我的代码,以便在第15次迭代中,代码不会添加逗号。如果它是一个循环迭代数组的简单循环,我可以使用iteritems()
来提取键和值并添加一个if条件,但在这里我无法弄清楚如何去做。
from pattern.web import URL, DOM, plaintext, extension
folder = '../some_folder'
dom = DOM(content)
print "traversing ... "
for e in dom('td.spgb-f')[:15]:
for a in e('span.sptc-e'):
File = open(os.path.join(folder, "meta_keywords.html"), mode="a")
print ('adding %s' %(plaintext(a.content)))
File.write(plaintext(a.content) + ", ")
File.close()
对不起,我没有看到你的答案,我发布之前。矿井本质上是一样的。 :) –