2016-04-01 45 views
0

我使用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() 

回答

2

不要考虑在每次迭代中追加一个逗号(您的分隔符),而应考虑将其作为预分隔符的另一种方式,该分隔符以空白开头,然后在第一个末尾设置为逗号值迭代你的循环。

separator='' 
for e in dom('td.spgb-f')[:15]: 
    for a in e('span.sptc-e'): 
     ... 
     print (separator + 'adding %s' %(plaintext(a.content))) 
     separator = ', ' 
+0

对不起,我没有看到你的答案,我发布之前。矿井本质上是一样的。 :) –

1

而不是写每个人的字符串的文件,你可以将它们添加到列表中,没有逗号,并使用", ".join(your_list_here)创建将被写入到文件中的字符串。方法join负责在元素之间放置逗号。

3

我会建议劳罗的答案,但在某些情况下,这样的列表可能不适合在内存和“流”的方式比较好。

然后你就可以代替试试这个:

first = True 
file = open(...) 
for a in e('span.sptc-e'): 
    if not first: 
     file.write(", ") 
    file.write(plaintext(a.content) + ", ") 
    first = False 
file.close() 

你不断打开和关闭文件,这是没有必要的。您可以在循环之前打开它,然后在完成时关闭它。这样做的最佳方式通常是使用'with'块:

with open(...) as file: 
    file.write(...) 
# The file is automatically closed after the block 
+0

我已经为您投票了 –

+0

谢谢,我很感激。 –