Hello,

I am trying to do a simple word count of a text file and output it to a text file.

For eg my array looks like this:

word_freq = [('test', 1), ('of', 1), ('function', 1), ('first', 1), ('the', 2)]

I was able to output to a text file in the following manner

[('word1', 3), ('word2', 2), ('word3', 1), ('word4', 1), ('word5', 2)]

How do I export to text file to look this:

word1 3
word2 2
word3 1
word4 1
word5 2

Thanks for your help.

Member Avatar for Mouche

Go through the list using a for loop, and in your print statement, reference the parts of the tuple using indices:

pairs = [('word1', 3), ('word2', 2), ('word3', 1), ('word4', 1), ('word5', 2)]

for pair in pairs:
    print pair[0],pair[1]
>>> s = [('word1', 3), ('word2', 2), ('word3', 1), ('word4', 1), ('word5', 2)]
>>> for i in s:
...     print '%s %s' % (i[0], i[1])
...     
word1 3
word2 2
word3 1
word4 1
word5 2
>>>

If writing to a file.

s = [('word1', 3), ('word2', 2), ('word3', 1), ('word4', 1), ('word5', 2)]
with open('new.txt', 'w') as f_out:
    for item in s:
        f_out.write('%s %s\n' % (item[0], item[1]))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.