技术咨询:如何输入国家名称后仅将对应英文缩写写入文件
Hey there! Let's break down your two questions one by one with practical code examples that you can use right away:
This is a straightforward task—you just need to define your target abbreviation and write it directly to a file. Here are examples in two common languages:
Python Example
# Define the abbreviation you want to write target_abbrev = "UK" # Open the file in write mode ("w" overwrites existing content; use "a" to append instead) with open("abbreviation_output.txt", "w") as output_file: output_file.write(target_abbrev)
The with statement ensures the file is properly closed after writing, which is good practice to avoid resource leaks.
Bash Example
If you're working in a terminal, you can use the echo command:
# Write abbreviation to file (overwrites existing content) echo "UK" > abbreviation_output.txt # To append instead of overwriting, use >> # echo "UK" >> abbreviation_output.txt
For this, you'll first need a mapping of country names to their abbreviations, then handle user input and look up the matching abbreviation. Here's how to do it:
Python Example
We'll use a dictionary to store the country-abbreviation pairs, and add some input handling to make it more robust:
# Create a dictionary of country names and their corresponding abbreviations country_abbrev_map = { "United Kingdom": "UK", "United States": "US", "China": "CN", "Germany": "DE", "France": "FR", # Add more countries as needed } # Get user input, clean it up (strip extra spaces, standardize capitalization) user_country = input("Please enter the country name: ").strip().title() # Look up the abbreviation and write to file if user_country in country_abbrev_map: selected_abbrev = country_abbrev_map[user_country] with open("country_abbrev_output.txt", "w") as output_file: output_file.write(selected_abbrev) print(f"Success! Wrote abbreviation '{selected_abbrev}' to file.") else: print("Sorry, I don't have an abbreviation for that country. Double-check your spelling!")
The .title() method ensures inputs like "united kingdom" or "UNITED KINGDOM" still match the dictionary keys.
Bash Example
Using a Bash associative array for the mapping:
# Declare an associative array for country-abbreviation pairs declare -A country_abbrev_map=( ["United Kingdom"]="UK" ["United States"]="US" ["China"]="CN" ["Germany"]="DE" ["France"]="FR" ) # Get user input read -p "Please enter the country name: " user_country # Standardize capitalization (Bash 4+) user_country=$(echo "$user_country" | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2));}1') # Look up and write to file if [[ -v country_abbrev_map["$user_country"] ]]; then selected_abbrev=${country_abbrev_map["$user_country"]} echo "$selected_abbrev" > country_abbrev_output.txt echo "Success! Wrote abbreviation '$selected_abbrev' to file." else echo "Sorry, I don't have an abbreviation for that country. Double-check your spelling!" fi
内容的提问来源于stack exchange,提问作者YaB0iZeuz




