# Do I need a next for loop in order to get all values?

When i print this in the module without printing to file, it prints all values. But when I print it to the designated file, it only prints the first value.

#Create the model base
from sklearn.feature_selection import chi2
import numpy as np
N = 2
for UNSPSC, category_id in sorted(category_to_id.items()):
features_chi2 = chi2(features, labels == category_id)
indices = np.argsort(features_chi2[0])
feature_names = np.array(tfidf.get_feature_names())[indices]
unigrams = [v for v in feature_names if len(v.split(' ')) == 1]
bigrams = [v for v in feature_names if len(v.split(' ')) == 2]

with open('results.csv', 'w') as f:
print("# '{}':".format(UNSPSC), file=f)
print("  . Most correlated unigrams:\n. {}".format('\n. '.join(unigrams[-N:])), file=f)
print("  . Most correlated bigrams:\n. {}".format('\n. '.join(bigrams[-N:])), file=f)


How can i adjust this so that all values get printed onto the file?

• You are writing values to a file, so yes you need to iter over the numpy array. After opening, iter over every Line and write correspondingly Apr 26 '18 at 16:38
• Would you be able to provide me the code for that? I tried a few examples from stackoverflow but couldnt get it to work. Apr 26 '18 at 18:16
• If you want to keep that file handy, then you can save it on your hardisk as a numpy array itself, search for . npz (saving numpy array) Apr 26 '18 at 18:19

Don't forget to open the file first..

Py 2.6

For item in list:
the_opened_file.write("%s\n" % item)


Py 3.x

with open(filepath,'w') as fileptr:
for item in list:
fileptr.write("{}\n".format(item))


If you want to save your list itself, Convert it to numpy format using np.assarray(list) and then use np.save(file,array,....(other opts) and reload it whenever required using np.load()