0

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.

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by snippsat
0

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]
0
>>> 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]))
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.