如何更改使用file()函数的代码块现在使用open()函数

时间:2017-10-13 01:34:27

标签: python machine-learning

我正在尝试遍历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

2 个答案:

答案 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