этот код должен быть игровым, он работает следующим образом. программа начинается со случайного слова, выбранного
из списка, затем мне нужно вставить любое слово, которое начинается с последней буквы последнего слова, но оно продолжает говорить, что оно недействительно
Код: Выделить всё
import random
import requests
from bs4 import BeautifulSoup
def load_words():
# load a list of words from a file or define them manually
return ["apple", "banana", "cherry", "date", "eggplant", "fig", "grape"]
def find_words_on_google(letter):
url = f"https://www.google.com/search?q=define+{letter}*"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
words = []
for element in soup.find_all("div", class_="BNeawe s3v9rd AP7Wnd"):
word = element.get_text()
if word.startswith(letter):
words.append(word)
return words # Moved the return statement outside the loop
def main():
print("Welcome to the Word Chain Game!")
print("Enter a word that starts with the same letter as the last letter of the previous word.")
print("Enter 'quit' to end the game")
# Randomly select a starting word
words = load_words()
current_word = random.choice(words)
print("Starting word:", current_word)
while True:
user_input = input("Your word: ").lower()
# Check if the user wants to quit
if user_input == "quit":
print("Thanks for playing!")
break
# Check if the user's input is valid
if user_input.startswith(current_word[-1]) and user_input in words and user_input != current_word:
# Find words starting with the last letter of the user's input from Google
google_words = find_words_on_google(user_input[-1])
if google_words:
print("Words from Google Dictionary:")
for word in google_words: # Changed the variable name to avoid confusion
print("-", word)
current_word = user_input
else:
print("No words found on Google Dictionary.")
else:
print("Invalid word. Try again.")
if __name__ == "__main__": # Corrected the condition
main()
Подробнее здесь: https://stackoverflow.com/questions/784 ... he-same-le