我正在尝试遍历feedlist.txt
,我了解file()
和open()
的使用方式相同。我试图用较旧的ML书进行练习。
apcount={}
wordcounts={}
for feedurl in file('feedlist.txt'):
title,wc=getwordcounts(feedurl)
wordcounts[title]=wc
for word,count in wc.items():
apcount.setdefault(word,0)
if count>1:
apcount[word]+=1
答案 0 :(得分:0)
看看这是否有帮助:
with open('feedlist.txt','r') as fp:
filecontent = fp.readlines()
title,wc = getwordcounts(filecontent)
wordcounts[title]=wc
for word,count in wc.items():
apcount.setdefault(word,0)
if count>1:
apcount[word]+=1
with
处理文件异常,仅在文件存在时执行with
后的命令。
答案 1 :(得分:0)
要循环显示每一行,就像在原始行中一样,这里使用open
等效。这将在离开with
块后关闭文件。与原文一样,一次只有一行传递给getwordcounts()
。
with open('feedlist.txt') as f:
for feedurl in f:
title,wc=getwordcounts(feedurl)
wordcounts[title]=wc
for word,count in wc.items():
apcount.setdefault(word,0)
if count>1:
apcount[word]+=1