0

I have script that opens and reads text file, separate every word and making a list of those words. I made Counter to count each word from list how many times does it appears. Then I want to export in .csv file each row something like this:

word hello appears 10 times

word house appears 5 times

word tree appears 3 times

...And so on

Can you show me what do I need to change here to make script to work?

from collections import Counter
import re
import csv

cnt = Counter()

writefile = open('test1.csv', 'wb')
writer = csv.writer(writefile)


with open('screenplay.txt') as file:       #Open .txt file with text
    text = file.read().lower()
    file.close()
    text = re.sub('[^a-z\ \']+', " ", text)
    words = list(text.split())             #Making list of each word
    for word in words:
        cnt[word] += 1                     #Counting how many times word appear
        for key, count in cnt.iteritems():
            key = text
            writer.writerow([cnt[word]]) 

1 Answer 1

1

The big issue is that your second for-loop is happening for every occurrence of every word, not just once for each unique word. You will need to de-dent the whole loop so that it executes after you have finished your counting. Try something like this:

from collections import Counter
import re
import csv

cnt = Counter()

writefile = open('test1.csv', 'wb')
writer = csv.writer(writefile)


with open('screenplay.txt') as file:
    text = file.read().lower()
    text = re.sub('[^a-z\ \']+', " ", text)
    words = list(text.split())
    for word in words:
        cnt[word] += 1
    for key, count in cnt.iteritems(): #De-dent this block
        writer.writerow([key,count]) #Output both the key and the count

writefile.close() #Make sure to close your file to guarantee it gets flushed
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It works, I was unorganized with code so I forgot for second loop to check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.