读取字典文件问题:实现公司名称与股票代码互查函数求助
Hey there! Let's get those two lookup functions working for you, plus tweak your existing tickers_to_dict to handle small edge cases (like leftover newline characters) that might break your lookups.
Step 1: Fix the tickers_to_dict Function
Your original code is close, but when using readlines(), each line includes a trailing newline (\n) which will get stuck in your ticker values. Let's fix that and also use Python's with statement to safely handle file closing:
def tickers_to_dict(filename): ticker_dict = {} # Use 'with' to auto-close the file after reading with open(filename, 'r') as bestand: for line in bestand: line = line.strip() # Remove newlines and extra whitespace if not line: # Skip empty lines if any exist continue # Split into name and symbol, then strip any leftover whitespace company_name, ticker_symbol = line.split(':') ticker_dict[company_name.strip()] = ticker_symbol.strip() return ticker_dict
Step 2: Implement name_to_symbol
This one’s straightforward—your dictionary already maps company names to ticker symbols directly. We’ll use the get() method to safely handle cases where the company name isn’t found:
def name_to_symbol(name, ticker_dict): # Return the symbol if the name exists, else a fallback message return ticker_dict.get(name, "Company name not found")
Step 3: Implement symbol_to_name
For this reverse lookup, we need to iterate through the dictionary’s items to find which company name matches the given symbol. For small datasets like yours, this is totally efficient:
def symbol_to_name(symbol, ticker_dict): for company_name, ticker_symbol in ticker_dict.items(): if ticker_symbol == symbol: return company_name # Fallback if the symbol doesn't exist return "Ticker symbol not found"
Test the Full Workflow
Here’s how you can use these functions to match your expected output:
# Load the ticker data from the file ticker_data = tickers_to_dict('ticker_symbol.txt') # Test name-to-symbol lookup user_company = input("Enter Company name: ") print(f"Ticker symbol: {name_to_symbol(user_company, ticker_data)}") # Test symbol-to-name lookup user_symbol = input("Enter Ticker symbol: ") print(f"Company name: {symbol_to_name(user_symbol, ticker_data)}")
Quick Notes:
- The
.strip()calls handle any accidental spaces in your input file (e.g., if a line hasYAHOO : YHOOinstead ofYAHOO:YHOO). - Using
with open(...)is a Python best practice—it ensures the file is closed automatically, even if an error occurs. - For larger datasets, you could pre-create a reversed dictionary (
symbol_to_name_map = {v: k for k, v in ticker_dict.items()}) to make reverse lookups instant, but that’s overkill for your current data.
内容的提问来源于stack exchange,提问作者programmer_66

