path = 'test.txt' #The preprocessed file with open(path,encoding='utf-8',newline='') as f: word = [] words_dict= {} for letter in f.read(): if letter.isalnum(): word.append(letter) elif letter.isspace(): if word: word = ''.join(word).lower() if word not in words_dict: words_dict[word] = 1 else: words_dict[word] += 1 word = [] if word: word = ''.join(word).lower() if word not in words_dict: words_dict[word] = 1 else: words_dict[word] += 1 word = [] f = open(""result.txt"", 'w') for k,v in words_dict.items(): print(k,v, file=f) for k,v in words_dict.items(): print((k,v), file=f) f.close()