-1

I am trying to print out the top 10 words from each cluster and I am struggling to save it to a file not sure how to save the content to the file without just built-in function. Here is my code. Could anyone please give suggestions. Thanks

Code:

l=['0','1','2','3','4']

for i in range(best_K):
    print(l[i],"Cluster top words:", end='')
    for ind in order_centroids[i, :10]: 
        word=vocab_frame.ix[terms[ind].split(' ')].values.tolist()[0][0]
        print(' %s' % word, end=',')
    print()

Tried 1:

In the text file i get <built-in function print>
l=['0','1','2','3','4']

order_centroids = model.cluster_centers_.argsort()[:, ::-1] 

for i in range(best_K):
    f = open("output.txt", "w")
    print(l[i],"Cluster top words:", end='')
    for ind in order_centroids[i, :10]: 
        word=vocab_frame.loc[terms[ind].split(' ')].values.tolist()[0][0]
        print(' %s' % word, end=',')
        my_top=str(print)
        f.write(my_top)
tripleee
  • 175,061
  • 34
  • 275
  • 318
KSp
  • 1,199
  • 1
  • 11
  • 29

2 Answers2

2
fp = open("test.txt",'a')

for i in range(best_K):
    print(l[i],"Cluster top words:", end='',, file=fp)
    for ind in order_centroids[i, :10]:
        word=vocab_frame.ix[terms[ind].split(' ')].values.tolist()[0][0]
        print(' %s' % word, end=',', file=fp)
    print(file=fp)
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
  • I am printing out a for loop and in place of 'your random string' how do i fit my print statement? – KSp Jun 27 '20 at 16:49
1

The Python print function actually handles this. Is there a reason you chose not to use a context manager to handle the setup/teardown of your file buffer?

l=['0','1','2','3','4']

order_centroids = model.cluster_centers_.argsort()[:, ::-1] 

with open("output.txt", "w") as f:
    for i in range(best_K):
        print(l[i], "Cluster top words:", end='', file=f)
        print(*[vocab_frame.loc[terms[ind].split(' ')].values.tolist()[0][0] for ind in order_centroids[i, :10]], sep=',', file=f)
hemmelig
  • 240
  • 2
  • 8