Python程序开发需求:基于字典文件实现英文到原住民语言翻译
Alright, let's build this English-to-Indigenous language translation program you need. Here's a practical Python solution that covers all your requirements, plus some helpful handling for common edge cases:
Step 1: Build the Translation Dictionary
First, we'll read the dictionary.txt file and convert its contents into a Python dictionary. We'll clean up any extra whitespace around words, and set up case-insensitive lookups so things like "I" and "i" both map to the correct translation.
Step 2: Handle User Input & Translation
Next, we'll accept input lines from the user until they enter a blank line. For each line, we'll split it into individual words, look each one up in our dictionary, and assemble the translated sentence. Any words that aren't in the dictionary will stay as their original form.
Full Working Code
import string def build_translation_dict(file_path): translation_dict = {} with open(file_path, 'r', encoding='utf-8') as f: for line in f: # Strip newline characters and extra spaces from the line cleaned_line = line.strip() if not cleaned_line: continue # Skip empty lines in the dictionary file # Split the line into English and Indigenous words english_word, indigenous_word = cleaned_line.split(',', 1) # Clean up whitespace and store in lowercase for case-insensitive lookup english_key = english_word.strip().lower() indigenous_value = indigenous_word.strip() translation_dict[english_key] = indigenous_value return translation_dict def translate_text(text, translation_dict): translated_words = [] # Split the input text into words, handling punctuation attached to words for word in text.split(): # Remove leading/trailing punctuation from the word cleaned_word = word.strip(string.punctuation).lower() # Look up the word - use original word if not found translated_word = translation_dict.get(cleaned_word, word) translated_words.append(translated_word) return ' '.join(translated_words) def main(): # Build the dictionary from the file try: trans_dict = build_translation_dict('dictionary.txt') except FileNotFoundError: print("Error: Could not find 'dictionary.txt' in the current directory.") return print("Enter text to translate (enter a blank line to exit):") while True: user_input = input("> ").strip() if not user_input: print("Exiting program.") break translated_sentence = translate_text(user_input, trans_dict) print(f"Translation: {translated_sentence}") if __name__ == "__main__": main()
Key Details Explained
- Case Insensitivity: By converting both the dictionary keys and input words to lowercase, we ensure that "Afternoon" and "afternoon" both translate to
wuraji-wuraji. - Punctuation Handling: The code strips punctuation from the start/end of words (like "bird!" becomes "bird" for lookup) but keeps the original punctuation attached to the translated word if the word isn't found.
- Error Handling: If
dictionary.txtis missing, the program will notify you instead of crashing. - Empty Lines: The program skips any empty lines in the dictionary file, so you don't have to worry about accidentally breaking the dictionary build.
How to Use
- Make sure your
dictionary.txtis in the same folder as the Python script, with each line formatted asEnglishWord,IndigenousWord(e.g.,afternoon,wuraji-wuraji,I,ngaju,bird,jir). - Run the script, enter lines of text to translate, and hit enter. When you're done, just press enter without typing anything to exit.
内容的提问来源于stack exchange,提问作者dumb_guy

