954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

printing array without ( ) ' [ ]

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.

pradark
Newbie Poster
1 post since Sep 2011
Reputation Points: 10
Solved Threads: 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]
LaMouche
Posting Whiz in Training
269 posts since Oct 2006
Reputation Points: 83
Solved Threads: 39
 
>>> 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]))
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: