[PYTHON] Create a bot that boosts Twitter trends

Do you have a time when you want to boost the Twitter trend?

In such a case, let's create a bot that automatically tweets by generating sentences from a specific tag in Python.

This time, I will omit the part of fetching sentences from Twitter and making sentences. Also, I have updated it about 3 times, The very first one is easy, so I'll explain it.

Parse

First, we need to extract the noun from Japanese. This time we will use a parsing library called janome.

janome is a tool that breaks down Japanese into syntax

from janome.tokenizer import Tokenizer

tokenizer = Tokenizer()

sentence = 'Today's guest was Mr. Wada.'

for token in tokenizer.tokenize(sentence):
    print(token)
    
#Today noun,Adverbs possible,*,*,*,*,today,Hongjitsu,Hongjitsu
#Particles,Attributive,*,*,*,*,of,No,No
#Guest noun,General,*,*,*,*,The guests,The guests,The guests
#Is a particle,Particle,*,*,*,*,Is,C,Wow
#Wada noun,Proper noun,Personal name,Surname,*,*,Wada,Wada,Wada
#San noun,suffix,Personal name,*,*,*,Mr.,Sun,Sun
#Deshi auxiliary verb,*,*,*,Special Death,Continuous form,is,Deci,Deci
#Auxiliary verb,*,*,*,Special,Uninflected word,Ta,Ta,Ta
#.. symbol,Kuten,*,*,*,*,。,。,。

It decomposes Japanese as follows.

Check for duplicates

You can break down one tweet with this, but this may cause noise.

Therefore, make a sentence only when the same noun exists in multiple tweets.

Some people like this. Screenshot.png

First, there is a class for duplicate extraction.

class DuplicateChecker:
    
    def __init__(self, tokenier: Tokenizer):
        self.twitt_nouns = []
        self.tokenier = tokenier

    def extract_duplications(self) -> [str]:
        return [x for x in set(self.twitt_nouns) if self.twitt_nouns.count(x) > 1]

    def input_twitt(self, twitt: str):
        tokens = self.tokenier.tokenize(twitt)
        
        nouns = []
        buffer = None
        for token in tokens:
            if token.part_of_speech.count("noun"):
                if buffer is None: 
                    buffer = ""
                buffer += token.surface
            else:
                if buffer is not None:
                    nouns.append(buffer)
                buffer = None
                    
                    
        self.twitt_nouns.extend(nouns)

Now, when I check for duplicates, it looks like this:

tokenier = Tokenizer()
duplicateChecker = DuplicateChecker(tokenier)

duplicateChecker.input_twitt("I felt the possibility of the striped pattern")
duplicateChecker.input_twitt('I only feel the possibility')
duplicateChecker.input_twitt('Feel the possibility')

nouns = duplicateChecker.extract_duplications()
nouns # ["possibility"]

(The production was also checked by the user.)

Sentence generation

Make a sentence from the noun extracted at the end. (This time is appropriate.)

class SentenceGenerator:
    
    def __init__(self, nouns:[str]):
        self.nouns = nouns
        self.senence_base = ["{}Is grass", "{}important", "{}", "{}Ne", "{}だNe", "{}!"]
        
    def generate(self) -> str:
        index:int = int(random.uniform(0, 200)) % len(self.senence_base)
        sentence = self.senence_base[index].format(self.nouns[0])
        return sentence

When executed, it looks like this. スクリーンショット 2.png

Summary

This time I tried to make something unreasonably simple. If there is a response, I will write how I updated it.

Recommended Posts

Create a bot that boosts Twitter trends
Create a slack bot
Steps to create a Twitter bot with python
Create a real-time auto-reply bot using the Twitter Streaming API
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create a LINE Bot in Django
Easy! Implement a Twitter bot that runs on Heroku in Python
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
[LINE Messaging API] Create a BOT that connects with someone with Python
Create a bot to retweet coronavirus information
[Python] [LINE Bot] Create a parrot return LINE Bot
Create a new dict that combines dicts
[Python] Create a LineBot that runs regularly
Let's make a Twitter Bot with Python!
Create a BOT that can call images registered with Discord like pictograms
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 2)
[Python] Created a Twitter bot that generates friend-like tweets using Markov chains
Create a bot with AWS Lambda that automatically starts / stops Instances with specific tags
A memo that I stumbled upon when doing a quote RT on Twitter Bot
Make a Twitter trend bot with heroku + Python
Mute Twitter trends and have a comfortable Twitter life! !!
Create a LINE BOT with Minette for Python
Create a page that loads infinitely with python
Get Twitter Trends
Create a BOT that displays the number of infected people in the new corona
Python: Create a class that supports unpacked assignment
Create a discord bot that notifies unilaterally with python (use only requests and json)
Create a fake class that also cheats is instance
Create a data collection bot in Python using Selenium
I made a Twitter BOT with GAE (python) (with a reference)
Make a BOT that shortens the URL of Discord
Create a chatbot that supports free input with Word2Vec
In Python, create a decorator that dynamically accepts arguments Create a decorator
Create a Django schedule
Create a bot that only returns the result of morphological analysis with MeCab on Discord
Create a Python module
Create a Python environment
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
Create a web application that recognizes numbers with a neural network
Create a PythonBox that outputs with Random after PEPPER Input
Create a QR code that displays "Izumi Oishi" by scratch
Create a plugin that always highlights arbitrary text in Sublime Text 2
I made a LINE BOT that returns parrots with Go
Create a list in Python with all followers on twitter
Create a machine learning app with ABEJA Platform + LINE Bot
Create a Mastodon bot with a function to automatically reply with Python
[Python] Create a linebot that draws any date on a photo
Let's create a script that registers with Ideone.com in Python.
Create a life game that is manually updated with tkinter
Let's create a Docker environment that stores Qiita trend information!
Create code that outputs "A and pretending B" in python
A barren Twitter posting client that saves only your tweets
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
I tried to create a bot for PES event notification
Create a correlation diagram from the conversation history of twitter