5

I want the text to be one key:count per line. Right now it saves the file just as a plain dictionary and I can't figure it out.

def makeFile(textSorted, newFile) :
dictionary = {}
counts = {}
for word in textSorted :
    dictionary[word] = counts
    counts[word] = counts.get(word, 0) + 1

# Save it to a file
with open(newFile, "w") as file :
    file.write(str(counts))
file.close()
return counts

4 Answers4

5

You can so this is a couple of lines with a CounterDict and the csv module:

import csv
def makeFile(textSorted, newFile) :
    from collections import Counter
    with open(newFile, "w") as f:
        wr = csv.writer(f,delimiter=":")
        wr.writerows(Counter(textSorted).items())

Using two dictionaries is pointless if you just want to store the key/value pairs. A single Counter dict will get the count for all the words and csv.writerows will write each pair separated by a colon one pairing per line.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

try this

def makeFile(textSorted, newFile) :
    counts = {}
    for word in textSorted :
        counts[word] = counts.get(word, 0) + 1

    # Save it to a file
    with open(newFile, "w") as file :
        for key,value in counts.items():
            file.write("%s:%s\n" % (key,value))
    return counts

EDIT: since iteritems is removed from python 3, change code to items()

Namit Singal
  • 1,506
  • 12
  • 26
  • I got this error - AttributeError: 'dict' object has no attribute 'iteritems' –  Jun 05 '15 at 23:50
  • are you using python 3? – Namit Singal Jun 05 '15 at 23:51
  • use items() instead of iteritems() for python3 iteritems was removed in python3 and items does the same thing as iteritems did in python2 – Namit Singal Jun 05 '15 at 23:52
  • Works perfectly! Thank you! Could you also explain the %s part to me please? I'm not familiar with it. –  Jun 05 '15 at 23:58
  • basically it is for string formatting, if I have a string and a number that i want in the string, I can do it like "%s for string and %d in number" % (string1, num) which string1 will replace %s and num will replace %d you can check http://stackoverflow.com/questions/997797/what-does-s-mean-in-python and – Namit Singal Jun 06 '15 at 00:02
  • Although ``"%s:%s\n" % (key,value)`` is not incorrect, I'd recommend replacing with ``"{}:{}\n".format(key, value)``. – pzp Jun 06 '15 at 00:10
  • I was a bit unaware of this, could you please explain the benefit of using it? – Namit Singal Jun 06 '15 at 00:16
  • @NamitSingal There are plenty of articles about it, but here's a pretty good [SO thread](http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) I found. In general, ``str.format()`` allows you to perform much more sophisticated formatting operations. Here's the [PEP describing the change](https://www.python.org/dev/peps/pep-3101/). – pzp Jun 06 '15 at 00:18
  • 2
    The point of using `with` is you don't need to close the file – Padraic Cunningham Jun 06 '15 at 00:30
  • @PadraicCunningham Did not notice the file.close() in the code, Just changed the loop, editted the answer. thanks, – Namit Singal Jun 06 '15 at 00:33
2

// Very basic dictionary to file printer

dictionary = {"first": "Hello", "second": "World!"}

with open("file_name.txt", "w") as file:

  for k, v in dictionary.items():

    dictionary_content = k + ": " + v + "\n"

    file.write(dictionary_content)
hamdev
  • 31
  • 1
0
x = open('a_file.txt','w')
x.write('\n'.join(str(your_dict).split(', ')))
x.close()