如何在TXT文件中按ID检索并拆分匹配行字段逐行展示?
Solution to Extract and Format Player Fields by ID
Hey there! I get it—printing the whole line works, but splitting out each field for clean, readable output is way better. Let's walk through a Python implementation that does exactly what you need, with clear explanations along the way.
Step-by-Step Implementation
First, here's a complete code example that reads your TXT file, searches for a target ID, and outputs each field in your desired format:
# Set the ID you want to search for target_id = "456" # Replace this with the actual ID you're querying found_players = 0 # Open your player file (update the file path to match your actual file) with open("players.txt", "r") as player_file: for line in player_file: # Remove extra whitespace/newlines and split the line into individual fields # Adjust the separator here if your fields use commas (split(',')), tabs (split('\t')), etc. player_data = line.strip().split() # Ensure the line has all 5 required fields to avoid errors if len(player_data) == 5: id_num, player_name, player_age, player_height, player_weight = player_data # Check if this line's ID matches our target if id_num == target_id: found_players += 1 # Print the formatted results as requested print(f"{found_players} player/s have been found:") print(f'Player ID: {id_num}') print(f'Player name: {player_name}') print(f'Age: {player_age}') print(f'Height: {player_height}') print(f'Weight: {player_weight}') # Handle the case where no matching ID was found if found_players == 0: print("No players found with that ID.")
Key Details to Adjust for Your File
- Field Separator: The code uses
split()which works for space-separated fields. If your file uses commas (e.g.,1,John,25,180,75), replacesplit()withsplit(','). For tab-separated values, usesplit('\t'). - File Path: Make sure
players.txtpoints to the correct location of your file (e.g.,C:/data/players.txton Windows or/home/user/players.txton Linux/macOS). - Target ID: Replace
"456"with the actual ID you want to search for—you could even modify the code to accept user input instead of hardcoding this.
Why This Works
- We use
with open()to safely read the file (it automatically closes the file when done). strip()removes any trailing newlines or extra spaces from each line.- Unpacking the
player_datalist into individual variables (id_num,player_name, etc.) lets us easily access each field for formatted output. - We count matches as we go, so the opening line correctly reflects how many players were found.
Optional Optimization for Large Files
If your TXT file is very large (thousands of lines), you can pre-load all players into a dictionary for faster future lookups:
player_dict = {} with open("players.txt", "r") as player_file: for line in player_file: player_data = line.strip().split() if len(player_data) == 5: id_num = player_data[0] player_dict[id_num] = player_data[1:] # Store name, age, height, weight under the ID # Now you can look up any ID instantly target_id = "456" if target_id in player_dict: name, age, height, weight = player_dict[target_id] print(f"1 player/s have been found:") print(f'Player ID: {target_id}') print(f'Player name: {name}') print(f'Age: {age}') print(f'Height: {height}') print(f'Weight: {weight}') else: print("No players found with that ID.")
This way, you only read the file once, and subsequent searches are nearly instant.
内容的提问来源于stack exchange,提问作者Tom Derwin




