I have strings of words and I want to find the frequency of each word group, print the words (doesn't matter if words appear multiple times), and the total frequency for each word group by each word.
PLEASE NOTE: In the solution, I don't want to use any loop like 'for' loop but arrive at same results.
For example, I have words as follows:
'abc'
'abc'
'abc'
'abc'
'xyz'
'xyz'
'tuf'
'pol'
'pol'
'pol'
'pol'
'pol'
'pol'
and need output as:
'abc', 4
'abc', 4
'abc', 4
'abc', 4
'xyz', 2
'xyz', 2
'tuf', 1
'pol', 6
'pol', 6
'pol', 6
'pol', 6
'pol', 6
'pol', 6
I am using python3 and I have tried this code and it doesn't work as expected:
curr_tk = None
tk = None
count = 0
for items in data:
line = items.strip()
file = line.split(",")
tk = file[0]
if curr_tk == tk:
count += 1
else:
if curr_tk:
print ('%s , %s' % (curr_tk, count))
count = 1
curr_tk = tk
#print last word
if curr_tk == tk:
print ('%s , %s' % (curr_tk,count))
The above code gives me output as:
'abc', 4
'xyz', 2
'tuf', 1
'pol', 6