Python 3读取文本文件前5列并提取温度相关数据的技术问询
Python 3 Solution to Extract First 5 Columns and Skip Irrelevant Text
Here's a practical approach to solve this problem. The core idea is to filter out non-data lines (like separators or headers) and then pull the first 5 columns from valid entries.
Approach
- Skip irrelevant lines: We'll ignore lines that are full of dashes (the separator) or start with header text like "Day" (since those don't contain your target temperature/date data).
- Extract valid columns: For lines that start with a date format (e.g.,
MM/DD), split the line into columns using whitespace and grab the first 5 entries. - Optional processing: You can extend this to immediately track the lowest temperature and its corresponding date/year right in the loop.
Example Code
def get_valid_data(file_path): valid_entries = [] # Track the lowest temperature and its details (customize as needed) lowest_temp = None lowest_temp_details = None with open(file_path, 'r') as file: for line in file: stripped_line = line.strip() # Skip empty lines if not stripped_line: continue # Skip separator lines (all dashes) if stripped_line.startswith('-'): continue # Skip header lines if stripped_line.startswith('Day'): continue columns = stripped_line.split() # Make sure we have at least 5 columns to avoid errors if len(columns) >= 5: first_five = columns[:5] valid_entries.append(first_five) # Example: Track the lowest temperature (assuming 4th column is temp, index 3) current_temp = int(first_five[3]) if lowest_temp is None or current_temp < lowest_temp: lowest_temp = current_temp lowest_temp_details = { 'date': first_five[0], 'year': first_five[2], 'temp': current_temp } print("Lowest record temperature details:", lowest_temp_details) return valid_entries # Replace with your actual file path file_path = 'weather_data.txt' data = get_valid_data(file_path) # Print all valid first 5 column entries print("\nValid first 5 column entries:") for entry in data: print(entry)
Customization Tips
- If your irrelevant lines have different patterns (e.g., other header keywords), adjust the skip conditions (like changing
startswith('Day')to match your actual header text). - Double-check the column indices for temperature/year based on your real data structure — in the example, we assumed the 4th column (index 3) is the temperature and the 3rd column (index 2) is the year, but you might need to tweak these.
内容的提问来源于stack exchange,提问作者user9572081
相关产品推荐
相关产品推荐

