Python

Python

Explore python code snippets and tutorials

Python

Python keyword generator function

<p>To create an SEO keyword generator function in Python, we&#39;ll need to use some natural language processing techniques to extract relevant keywords from the input text. In this case, we&#39;ll …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# keyword_generator/utils.py
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer

nltk.download('punkt')
nltk.download('stopwords')

def generate_keywords(text):
    # Tokenize the text into words
    words = word_tokenize(text)

    # Remove stopwords (common words like "the", "is", "and", etc.)
    stop_words = set(stopwords.words('english'))
    words = [word.lower() for word in words if word.lower() not in stop_words]

    # Stemming the words (converting words to their root form)
    stemmer = PorterStemmer()
    stemmed_words = [stemmer.stem(word) for word in words]

    # Count word frequencies
    word_freq = {}
    for word in stemmed_words:
        word_freq[word] = word_freq.get(word, 0) + 1

    # Sort the words by frequency in descending order
    sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)

    # Return the top 10 keywords (you can adjust this number as needed)
    return [word for word, _ in sorted_words[:10]]
Python

Python requests check status code

<p>You can use the Python <code>requests</code> library to check if the status code of a URL is 200 without actually downloading the file content. When you make a request using …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import requests

def check_url_status(url):
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            print("URL is accessible (status code 200).")
        else:
            print(f"URL is not accessible. Status code: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")

# Example usage:
url_to_check = "https://example.com/somefile.txt"
check_url_status(url_to_check)