0
import re

from collections import Counter

words = re.findall(r'\w+', open('test01_cc_sharealike.txt').read().lower())
count = Counter(words).most_common(10)


print(count)

How can I change the code so it will format into like this:

Word   number

word   number

instead of a list

I want the format to be: the word first then 4 whitespace and the number of the word it appears on the text and so on

  • 1
    Should find what you need here: https://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data – Pythonista May 30 '17 at 18:36

1 Answers1

0

Just use a for loop, so instead of print(count), you could use:

for p in count:
    print(p[0]+"    "+str(p[1]))

However, for formatting purposes, you would probably prefer to align the numbers, so you should use:

indent=1+max([len(p[0]) for p in count])

for p in count:
    print(p[0].rjust(indent)+str(p[1]))
  • Strings have `.ljust` and `.rjust` methods, so you don't need to build a string of spaces with `" "*(indent-len(p[0]))`. Also, it's generally better to use `format` (or another one of Python's string formatting techniques) rather than manually converting and concatenating your output data. – PM 2Ring May 30 '17 at 18:43