Python:输出文本缩进及在线词典定义获取脚本技术咨询
Hey there! Let's walk through how to refine your Wiktionary definition script—both fixing up the indentation implementation and boosting its overall functionality. Here are practical, actionable tips:
Right now you’re hardcoding \t characters, which gets messy if you ever want to adjust indent size (like switching to spaces instead). Instead, use reusable variables or Python’s built-in tools for consistency:
Option 1: Use Indent Variables
Define your indent levels once, so you can tweak them in one place later:
# Define reusable indent levels (follows PEP8 for readability) INDENT_1 = "\t" INDENT_2 = "\t\t" # Then use them in your output print(f"\n{INDENT_1}\"{Word}\" {Type}") print(f"{INDENT_2}{Define(Word)}")
Option 2: Use textwrap.indent for Dynamic Indenting
If your definitions are multi-line, the textwrap module makes indentation trivial without manual string concatenation:
import textwrap # After fetching your definition word_header = f'"{Word}" {Type}' indented_output = textwrap.indent(f"{word_header}\n{Define(Word)}", "\t") print("\n" + indented_output)
Your current code assumes the user will enter exactly 3 arguments—if they don’t, it’ll throw an IndexError. Add basic validation to make it robust:
user_input = input('Define: ').strip().split() if len(user_input) != 3: print("Oops! Please enter in this format: <word> <part-of-speech> <number-of-definitions>") exit() # Use more descriptive variable names (PEP8 compliant) target_word, part_of_speech, num_defs = user_input
Assuming your Define() function handles scraping, here’s how to make it more stable (since Wiktionary’s HTML can change, and raw requests might get blocked):
import requests from bs4 import BeautifulSoup def get_wiktionary_definition(word, pos, max_defs): url = f"https://en.wiktionary.org/wiki/{word}" # Add a user-agent to avoid being blocked as a bot headers = {"User-Agent": "MyDefinitionScript/1.0 (contact@example.com)"} try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # Raise error for 4xx/5xx status codes except requests.exceptions.RequestException as e: return f"Failed to fetch definition: {str(e)}" soup = BeautifulSoup(response.text, "html.parser") # Find the part-of-speech section (e.g., "Noun", "Verb") pos_section = soup.find("span", class_="mw-headline", string=pos.capitalize()) if not pos_section: return f"No {pos} definitions found for '{word}'." # Extract the list of definitions (adjust selector if Wiktionary's structure changes) def_list = pos_section.find_next("ol") if not def_list: return f"No definitions listed for {pos} section of '{word}'." # Grab only the requested number of definitions definitions = [li.text.strip() for li in def_list.find_all("li")[:int(max_defs)]] return "\n".join([f"- {def}" for def in definitions])
Make the final output easier to scan with small formatting touches:
print("\n" + "="*60) print(f"{INDENT_1}\"{target_word}\" ({part_of_speech})") print(f"{INDENT_1}Top {num_defs} definitions:") print(f"{INDENT_2}{get_wiktionary_definition(target_word, part_of_speech, num_defs)}") print("="*60)
These changes will make your script more maintainable, less error-prone, and nicer to use!
内容的提问来源于stack exchange,提问作者voices

