how can i fix this issue "NameError: name 'f' is not defined" here is my function

Viewed 1761

my code is having issues where I don't know how to define f so that my code can work properly. please help.

stopwords = []
try:
    f = open("https://github.com/Yoast/YoastSEO.js/blob/develop/src/config/stopwords.js", 'r')
    stopwords = f.read().split('\n')
except IOError:
    print('Problem opening file')
finally:
    f.close()
print('Sentence before stopwrods removed: \n', tokenized[51])
filtered = []
for t in tokenized:
    text = t[0]
    f_text = []
    for word in text:
        if word not in stopwords and len(word) > 2:
            f_text.append(word)
    filtered.append((f_text, t[1]))

print('\nSentence after stopwords removed: \n', filtered[51]
2 Answers
stopwords = []

try:
    f = open("https://github.com/Yoast/YoastSEO.js/blob/develop/src/config/stopwords.js", 'r')
    stopwords = f.read().split('\n')
except IOError:
    print('Problem opening file')
else:
    f.close()
print('Sentence before stopwrods removed: \n', tokenized[51])
filtered = []
for t in tokenized:
    text = t[0]
    f_text = []
    for word in text:
        if word not in stopwords and len(word) > 2:
            f_text.append(word)
    filtered.append((f_text, t[1]))

print('\nSentence after stopwords removed: \n', filtered[51])

You should consider using the with clause. It makes sure the file is closed in any case, if it is necessary. So in the code below the except clause is only used to print the error text.

stopwords = []
try:
    with open("https://github.com/Yoast/YoastSEO.js/blob/develop/src/config/stopwords.js", 'r') as f:
        stopwords = f.read().split('\n')
except IOError:
    print('Problem opening file')
print('Sentence before stopwrods removed: \n', tokenized[51])
filtered = []
for t in tokenized:
    text = t[0]
    f_text = []
    for word in text:
        if word not in stopwords and len(word) > 2:
            f_text.append(word)
    filtered.append((f_text, t[1]))

print('\nSentence after stopwords removed: \n', filtered[51]
Related