Python script to group hashtags

Shaybib

Senior Member
Joined
Mar 23, 2018
Messages
831
Reaction score
262
How do i make a script that takes a long list of hashtags from file and write them to another file in groups of ten hashtags to a line?
 
Code:
from itertools import zip_longest


def grouper(iterable, n, fillvalue=None):
    """Collect data into fixed-length chunks or blocks.

    Example:
        >>> grouper('ABCDEFG', 3, 'x')  # => ['ABC', 'DEF', 'Gxx']
    """

    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


with open('hashtags.txt', mode='r', encoding='utf-8') as f:
    # Save only unique hashtags.
    hashtags = set([line.strip() for line in f])

for counter, group in enumerate(grouper(hashtags, 10), start=1):
    with open(f'hashtags_{counter}.txt', mode='w', encoding='utf-8') as f:
        f.write('\n'.join([hashtag for hashtag in group if hashtag]))

This script will read hashtags.txt file and create files like hashtags_1.txt, hashtags_2.txt and so on.
Tested with Python 3.7.3.
 
Thanks! Ill give it a try
 
Back
Top