Advertisement
Python253

toprising

Apr 5th, 2024
629
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.63 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: toprising.py
  4. # Version: 0.0.2
  5. # Author: Jeoi Reqi
  6. # Date: February 2024
  7.  
  8. """
  9. This script provides functionality to retrieve and display related topics, including top and rising queries, for specified keywords using the Google Trends API.
  10.  
  11. Functions:
  12.    - display_related_data(pytrends, keywords, num_related_top, num_related_rising): Retrieves and displays related topics, including top and rising queries, for specified keywords.
  13.    - get_ports_name(pid): Retrieves the process name associated with a given process ID (PID).
  14.    - display_ports_in_use(ports_in_use): Displays the list of ports currently in use along with their associated processes and programs.
  15.  
  16. Features:
  17.    - Uses the Google Trends API (via pytrends library) to retrieve related topics, top queries, and rising queries for specified keywords.
  18.    - Supports input of up to 5 topics/keywords.
  19.    - Allows users to specify the number of months to gather data and the number of top and rising related topics to display.
  20.    - Provides the option to save the displayed data to a text file.
  21.  
  22. Requirements:
  23.    - Python 3.x
  24.    - pytrends library (install via pip: pip install pytrends)
  25.    - tabulate library (install via pip: pip install tabulate)
  26.  
  27. Usage:
  28.    1. Ensure Python 3.x is installed on your system.
  29.    2. Install the pytrends library by running: pip install pytrends
  30.    3. Install the tabulate library by running: pip install tabulate
  31.    4. Save the script as 'toprising.py'.
  32.    5. Execute the script using the command: python toprising.py
  33.    6. Follow the prompts to input topics, number of months, and related topics to display.
  34.  
  35. Notes:
  36.    - This script relies on the pytrends library to interact with the Google Trends API.
  37.    - The script prompts the user to input topics, the number of months to gather data, and the number of related topics to display.
  38.    - It uses the tabulate library to format and display the related data in a tabular format.
  39.    - The displayed data includes both top and rising related queries for each specified keyword.
  40.    - The script provides the option to save the displayed data to a text file for later reference.
  41. """
  42.  
  43. from pytrends.request import TrendReq
  44. from tabulate import tabulate
  45. from typing import List
  46. import sys
  47.  
  48. # [CONSTANTS]
  49. # Set the constant max values for topics & results
  50. max_topics = 5
  51. max_top = 24
  52. max_rising = 24
  53. max_months = 240
  54.  
  55. # GET RELATED (TOP/RISING) DATA
  56. def display_related_data(pytrends, keywords, num_related_top, num_related_rising):
  57.     """
  58.    Display related topics, including top and rising queries, for specified keywords.
  59.  
  60.    Parameters:
  61.    - pytrends (TrendReq): Google Trends API object.
  62.    - keywords (List[str]): List of keywords to retrieve related data for.
  63.    - num_related_top (int): Number of top related queries to display.
  64.    - num_related_rising (int): Number of rising related queries to display.
  65.  
  66.    Returns:
  67.    - str: 'return' if user chooses to return to the main program, 'end' if user chooses to end the program.
  68.    """
  69.     # Display related topics
  70.     print("\n\t\t\t::GATHERING RELATED TOPICS::\n\t\t    This may take some time to process...\n")
  71.  
  72.     terminal_output = ""  # Store the terminal output in a variable
  73.  
  74.     for keyword in keywords:
  75.         try:
  76.             # Create pytrends object inside the function
  77.             pytrends_local = TrendReq(hl='en-US', tz=-480)
  78.             pytrends_local.build_payload([keyword], timeframe=f'today {num_months}-m')  # Use user input for timeframe
  79.             related_queries_top = pytrends_local.related_queries()[keyword]['top'].head(num_related_top)
  80.             if not related_queries_top.empty:
  81.                 terminal_output += f"\nTop queries for '{keyword}':\n"
  82.                 # Store top related queries in tabular form
  83.                 terminal_output += tabulate(related_queries_top, headers='keys', tablefmt='pretty') + '\n'
  84.             else:
  85.                 terminal_output += f"\nNo top related queries found for '{keyword}'.\n"
  86.         except Exception as e:
  87.             terminal_output += f"Failed to get top related queries. Error: {e}\n"
  88.  
  89.         try:
  90.             related_queries_rising = pytrends_local.related_queries()[keyword]['rising'].head(num_related_rising)
  91.             if not related_queries_rising.empty:
  92.                 terminal_output += f"\nRising queries for '{keyword}':\n"
  93.                 # Store rising related queries in tabular form
  94.                 terminal_output += tabulate(related_queries_rising, headers='keys', tablefmt='pretty') + '\n'
  95.             else:
  96.                 terminal_output += f"\nNo rising related queries found for '{keyword}'.\n"
  97.         except Exception as e:
  98.             terminal_output += f"Failed to get rising related queries. Error: {e}\n"
  99.  
  100.     # Display the stored terminal output
  101.     print(terminal_output)
  102.  
  103.     # Ask if the user wants to save the data
  104.     save_option = input("\nDo you want to save the displayed data?\n1: Yes\n2: No\nYour Choice (1 or 2): ")
  105.     if save_option == '1':
  106.         # Save output to a dynamic named file
  107.         filename = '_'.join(keywords) + '_related_data.txt'
  108.         with open(filename, 'w', encoding='utf-8') as f:
  109.             f.write("\n::DISPLAYED RELATED DATA::\n\n")
  110.             f.write(f"Number of related top queries displayed: {num_related_top}\n")
  111.             f.write(f"Number of related rising queries displayed: {num_related_rising}\n")
  112.             f.write("\n::TERMINAL OUTPUT::\n\n")
  113.             f.write(terminal_output)
  114.         print(f"\nOutput saved to file: {filename}")
  115.         print("Program Exiting, Goodbye!")
  116.         sys.exit(0)
  117.     elif save_option == '2':
  118.         print("Program Exiting, Goodbye!")
  119.         sys.exit(0)
  120.     else:
  121.         print("\nInvalid option. Data not saved.")
  122.  
  123. # Allow the user to input up to 5 topics
  124. keywords: List[str] = []
  125. while True:
  126.     try:
  127.         num_topics = int(input(f"\nEnter the number of topics (1 to {max_topics}): "))
  128.         if 1 <= num_topics <= max_topics:
  129.             for i in range(num_topics):
  130.                 keyword = input(f"Enter topic/query {i+1}: ")
  131.                 keywords.append(keyword)
  132.         else:
  133.             print(f"\nInvalid number of topics. Please enter a number between 1 and {max_topics}.\n")
  134.     except ValueError:
  135.         print("\nInvalid input. Please enter a valid number.\n")
  136.     if 1 <= len(keywords) <= max_topics:
  137.         break
  138.  
  139. # Allow the user to input the number of months to gather
  140. try:
  141.     num_months = int(input(f"\nEnter the number of months to gather data (1 to {max_months}): "))
  142.     if 0 < num_months <= max_months:
  143.         # Allow the user to input the number of top and related topics (0 to 240)
  144.         num_top_related_topics = int(input(f"\nEnter the number of Top Related topics to display (0 to {max_top}): "))
  145.         if 0 <= num_top_related_topics <= max_top:
  146.             num_rising_related_topics = int(input(f"\nEnter the number of Rising Related topics to display (0 to {max_rising}): "))
  147.             if 0 <= num_rising_related_topics <= max_rising:
  148.                 if num_top_related_topics > 0 or num_rising_related_topics > 0:
  149.                     # Fetch data for topics
  150.                     try:
  151.                         pytrends = TrendReq(hl='en-US', tz=-480)
  152.                         pytrends.build_payload(keywords, timeframe=f'today {num_months}-m')  # Max: 240 months
  153.                         # Function to display and handle related data
  154.                         result = display_related_data(pytrends, keywords, num_top_related_topics, num_rising_related_topics)
  155.                         if result == 'return':
  156.                             print("Returned from the external script. Continue with the main program.")
  157.                         elif result == 'end':
  158.                             print("Ending the program. Goodbye!")
  159.                             sys.exit(0)
  160.                     except Exception as e:
  161.                         print(f"Failed to fetch data from Google Trends. Error: {e}")
  162.                 else:
  163.                     print("\nNo related topics to display.\n")
  164.             else:
  165.                 print(f"\nInvalid number of Rising Related topics. Please enter a number between 0 and {max_rising}.\n")
  166.         else:
  167.             print(f"\nInvalid number of Top Related topics. Please enter a number between 0 and {max_top}.\n")
  168.     else:
  169.         print(f"\nInvalid number of months. Please enter a number between 1 and {max_months}.\n")
  170. except ValueError:
  171.     print("\nInvalid input. Please enter a valid number.\n")
  172.  
  173. # DEBUG
  174. # Ignore warnings for redefining variables from the outer scope.
  175. # pylint: disable=redefined-outer-name
  176.  
  177.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement