Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: toprising.py
- # Version: 0.0.2
- # Author: Jeoi Reqi
- # Date: February 2024
- """
- This script provides functionality to retrieve and display related topics, including top and rising queries, for specified keywords using the Google Trends API.
- Functions:
- - display_related_data(pytrends, keywords, num_related_top, num_related_rising): Retrieves and displays related topics, including top and rising queries, for specified keywords.
- - get_ports_name(pid): Retrieves the process name associated with a given process ID (PID).
- - display_ports_in_use(ports_in_use): Displays the list of ports currently in use along with their associated processes and programs.
- Features:
- - Uses the Google Trends API (via pytrends library) to retrieve related topics, top queries, and rising queries for specified keywords.
- - Supports input of up to 5 topics/keywords.
- - Allows users to specify the number of months to gather data and the number of top and rising related topics to display.
- - Provides the option to save the displayed data to a text file.
- Requirements:
- - Python 3.x
- - pytrends library (install via pip: pip install pytrends)
- - tabulate library (install via pip: pip install tabulate)
- Usage:
- 1. Ensure Python 3.x is installed on your system.
- 2. Install the pytrends library by running: pip install pytrends
- 3. Install the tabulate library by running: pip install tabulate
- 4. Save the script as 'toprising.py'.
- 5. Execute the script using the command: python toprising.py
- 6. Follow the prompts to input topics, number of months, and related topics to display.
- Notes:
- - This script relies on the pytrends library to interact with the Google Trends API.
- - The script prompts the user to input topics, the number of months to gather data, and the number of related topics to display.
- - It uses the tabulate library to format and display the related data in a tabular format.
- - The displayed data includes both top and rising related queries for each specified keyword.
- - The script provides the option to save the displayed data to a text file for later reference.
- """
- from pytrends.request import TrendReq
- from tabulate import tabulate
- from typing import List
- import sys
- # [CONSTANTS]
- # Set the constant max values for topics & results
- max_topics = 5
- max_top = 24
- max_rising = 24
- max_months = 240
- # GET RELATED (TOP/RISING) DATA
- def display_related_data(pytrends, keywords, num_related_top, num_related_rising):
- """
- Display related topics, including top and rising queries, for specified keywords.
- Parameters:
- - pytrends (TrendReq): Google Trends API object.
- - keywords (List[str]): List of keywords to retrieve related data for.
- - num_related_top (int): Number of top related queries to display.
- - num_related_rising (int): Number of rising related queries to display.
- Returns:
- - str: 'return' if user chooses to return to the main program, 'end' if user chooses to end the program.
- """
- # Display related topics
- print("\n\t\t\t::GATHERING RELATED TOPICS::\n\t\t This may take some time to process...\n")
- terminal_output = "" # Store the terminal output in a variable
- for keyword in keywords:
- try:
- # Create pytrends object inside the function
- pytrends_local = TrendReq(hl='en-US', tz=-480)
- pytrends_local.build_payload([keyword], timeframe=f'today {num_months}-m') # Use user input for timeframe
- related_queries_top = pytrends_local.related_queries()[keyword]['top'].head(num_related_top)
- if not related_queries_top.empty:
- terminal_output += f"\nTop queries for '{keyword}':\n"
- # Store top related queries in tabular form
- terminal_output += tabulate(related_queries_top, headers='keys', tablefmt='pretty') + '\n'
- else:
- terminal_output += f"\nNo top related queries found for '{keyword}'.\n"
- except Exception as e:
- terminal_output += f"Failed to get top related queries. Error: {e}\n"
- try:
- related_queries_rising = pytrends_local.related_queries()[keyword]['rising'].head(num_related_rising)
- if not related_queries_rising.empty:
- terminal_output += f"\nRising queries for '{keyword}':\n"
- # Store rising related queries in tabular form
- terminal_output += tabulate(related_queries_rising, headers='keys', tablefmt='pretty') + '\n'
- else:
- terminal_output += f"\nNo rising related queries found for '{keyword}'.\n"
- except Exception as e:
- terminal_output += f"Failed to get rising related queries. Error: {e}\n"
- # Display the stored terminal output
- print(terminal_output)
- # Ask if the user wants to save the data
- save_option = input("\nDo you want to save the displayed data?\n1: Yes\n2: No\nYour Choice (1 or 2): ")
- if save_option == '1':
- # Save output to a dynamic named file
- filename = '_'.join(keywords) + '_related_data.txt'
- with open(filename, 'w', encoding='utf-8') as f:
- f.write("\n::DISPLAYED RELATED DATA::\n\n")
- f.write(f"Number of related top queries displayed: {num_related_top}\n")
- f.write(f"Number of related rising queries displayed: {num_related_rising}\n")
- f.write("\n::TERMINAL OUTPUT::\n\n")
- f.write(terminal_output)
- print(f"\nOutput saved to file: {filename}")
- print("Program Exiting, Goodbye!")
- sys.exit(0)
- elif save_option == '2':
- print("Program Exiting, Goodbye!")
- sys.exit(0)
- else:
- print("\nInvalid option. Data not saved.")
- # Allow the user to input up to 5 topics
- keywords: List[str] = []
- while True:
- try:
- num_topics = int(input(f"\nEnter the number of topics (1 to {max_topics}): "))
- if 1 <= num_topics <= max_topics:
- for i in range(num_topics):
- keyword = input(f"Enter topic/query {i+1}: ")
- keywords.append(keyword)
- else:
- print(f"\nInvalid number of topics. Please enter a number between 1 and {max_topics}.\n")
- except ValueError:
- print("\nInvalid input. Please enter a valid number.\n")
- if 1 <= len(keywords) <= max_topics:
- break
- # Allow the user to input the number of months to gather
- try:
- num_months = int(input(f"\nEnter the number of months to gather data (1 to {max_months}): "))
- if 0 < num_months <= max_months:
- # Allow the user to input the number of top and related topics (0 to 240)
- num_top_related_topics = int(input(f"\nEnter the number of Top Related topics to display (0 to {max_top}): "))
- if 0 <= num_top_related_topics <= max_top:
- num_rising_related_topics = int(input(f"\nEnter the number of Rising Related topics to display (0 to {max_rising}): "))
- if 0 <= num_rising_related_topics <= max_rising:
- if num_top_related_topics > 0 or num_rising_related_topics > 0:
- # Fetch data for topics
- try:
- pytrends = TrendReq(hl='en-US', tz=-480)
- pytrends.build_payload(keywords, timeframe=f'today {num_months}-m') # Max: 240 months
- # Function to display and handle related data
- result = display_related_data(pytrends, keywords, num_top_related_topics, num_rising_related_topics)
- if result == 'return':
- print("Returned from the external script. Continue with the main program.")
- elif result == 'end':
- print("Ending the program. Goodbye!")
- sys.exit(0)
- except Exception as e:
- print(f"Failed to fetch data from Google Trends. Error: {e}")
- else:
- print("\nNo related topics to display.\n")
- else:
- print(f"\nInvalid number of Rising Related topics. Please enter a number between 0 and {max_rising}.\n")
- else:
- print(f"\nInvalid number of Top Related topics. Please enter a number between 0 and {max_top}.\n")
- else:
- print(f"\nInvalid number of months. Please enter a number between 1 and {max_months}.\n")
- except ValueError:
- print("\nInvalid input. Please enter a valid number.\n")
- # DEBUG
- # Ignore warnings for redefining variables from the outer scope.
- # pylint: disable=redefined-outer-name
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement