Home > front end >  how to pass user defined string in tweet cursor search
how to pass user defined string in tweet cursor search

Time:04-17

Q)how to pass user defined string in tweet_cursor search i am trying to get tweets as per the user by taking input in a and passing variable a please help

currently it is searching for only a literally instead of variable a defined by user

`import textblob import pandas as pd import matplotlib.pyplot as plt import re

api_key = 'xxxxxxxxxxxx'
api_key_secret = 'xxxxxxxxxxx'
access_token = 'xxxxxxxxxxx'
access_token_secret = 'xxxxxxxxxxxxxxxxxxx'

authenticator = tweepy.OAuthHandler(api_key, api_key_secret)
authenticator.set_access_token(access_token, access_token_secret)

api = tweepy.API(authenticator, wait_on_rate_limit=True)

a=input(print("enter player name"))

search= f'#(a) -filter:retweets lang:en'

tweet_cursor = tweepy.Cursor(api.search_tweets, q=search, tweet_mode='extended').items(100)

tweets = [tweet.full_text for tweet in tweet_cursor]

tweets_df = pd.DataFrame(tweets, columns=['Tweets'])

for _, row in tweets_df.iterrows():
    row['tweets'] = re.sub('https\S ', '', row['Tweets'])
    row['tweets'] = re.sub('#\S ', '', row['Tweets'])
    row['tweets'] = re.sub('@\S ', '', row['Tweets'])
    row['tweets'] = re.sub('\\n', '', row['Tweets'])
print(tweets_df)
print(tweets)


tweets_df['Polarity'] = tweets_df['Tweets'].map(lambda tweet: textblob.TextBlob(tweet).sentiment.polarity)
tweets_df['Result'] = tweets_df['Polarity'].map(lambda pol: ' ' if pol > 0 else '-')

positive = tweets_df[tweets_df.Result == ' '].count()['Tweets']
negative = tweets_df[tweets_df.Result == '-'].count()['Tweets']

print(positive)
print(negative)
langs = ['Positive', 'Negative']
students = [positive,negative]
a=plt.bar(langs,students)
a[0].set_color('g')
a[1].set_color('r')

plt.xlabel("Tweet Sentiment")
plt.ylabel("No. of Tweets")
plt.title("Sentiment Analysis")
plt.legend

plt.show() `

CodePudding user response:

In Python f-Strings, you have to use curly braces around the variable.

search = f'#{a} -filter:retweets lang:en

But this will search for retweets containing the hashtag a.

If you want to search from the tweets of the user a, you should use:

search = f'from:{a} -filter:retweets lang:en

Please see the Twitter API documentation for all the search operators.

  • Related