I'm trying to make a python script that takes a string and gives the count of consecutive words. Let's say:
string = " i have no idea how to write this script. i have an idea."
output =
['i', 'have'] 2
['have', 'no'] 1
['no', 'idea'] 1
['idea', 'how'] 1
['how', 'to'] 1
['to', 'write'] 1
...
I'm trying to use python without importing collections, counters from collections. What I have is below. I'm trying to use a re.findall(#whatpatterndoiuse, string)
to iterate through the string and compare it but I'm having difficulties figuring out how to.
string2 = re.split('\s+', string. lower())
freq_dict = {} #empty dictionary
for word in word_list:
word = punctuation.sub("", word)
freq_dic[word] = freq_dic.get(word,0) + 1
freq_list = freq_dic.items()
freq_list.sort()
for word, freq in freq_list:
print word, freq
Using counter from collections which I did not want. Also it produce an output in a format that is not the one I stated above.
import re
from collections import Counter
words = re.findall('\w+', open('a.txt').read())
print(Counter(zip(words,words[1:])))