Python:如何按类型分割多行文本并按日期分类结果至数组?
Let's tackle each of your questions step by step, using Python for concrete examples (it's ideal for this kind of string and data structure work):
1. How to split the text by type/date blocks?
First, let's break down the input string into individual elements, then use date keywords (Monday-Sunday) to split the text into date-specific chunks:
text = '''Monday 1-t type1 2-d type2 Tuesday 1-t type1 2-d type2 3-rd type3 4-th type4 Wednesday 1-t type1 Thursday 1-t type1 2-d type2 3-rd type3 4-th type4 Friday 2-d type2 3-rd type3 4-th type4 Saturday 2-d type2 3-rd type3 Sunday 1-t type1 2-d type2''' # Split the entire text into a list of individual tokens tokens = text.split() # Define date markers to split the text around date_keywords = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] # Group tokens into date-based blocks date_blocks = [] current_block = [] for token in tokens: if token in date_keywords and current_block: date_blocks.append(current_block) current_block = [token] else: current_block.append(token) date_blocks.append(current_block) # Add the final block # Each block now looks like: ['Monday', '1-t', 'type1', '2-d', 'type2']
If you want to extract just the typeX entries from each block, filter them like this:
for block in date_blocks: types = [item for item in block if item.startswith('type')] print(f"{block[0]}'s types: {types}")
2. How to categorize the text by date (e.g., monday = [types..])?
There are a few practical ways to do this, depending on your needs:
Method 1: Use a Dictionary (Recommended)
A dictionary maps each date directly to its list of types, making it easy to access and maintain:
date_type_map = {} for block in date_blocks: date = block[0] types = [item for item in block if item.startswith('type')] date_type_map[date] = types # Access types for any date print(date_type_map['Monday']) # Output: ['type1', 'type2'] print(date_type_map['Tuesday']) # Output: ['type1', 'type2', 'type3', 'type4']
Method 2: Create Individual Variables (Less Flexible)
If you specifically need separate variables for each date, you can dynamically create them (note: this is not ideal for most projects):
for block in date_blocks: date_var_name = block[0].lower() # Convert to lowercase for valid variable names types = [item for item in block if item.startswith('type')] globals()[date_var_name] = types # Now you can use variables like monday, tuesday, etc. print(monday) # Output: ['type1', 'type2'] print(tuesday) # Output: ['type1', 'type2', 'type3', 'type4']
Method 3: Wrap in a Class (For Structured Projects)
For larger projects, organizing the data in a class keeps things clean:
class WeeklyTypeTracker: def __init__(self, date_type_dict): for date, types in date_type_dict.items(): setattr(self, date.lower(), types) tracker = WeeklyTypeTracker(date_type_map) print(tracker.monday) # Output: ['type1', 'type2']
3. How to store the categorized data in an array?
If by "array" you mean a Python list (the standard array-like structure), here are a few options:
Option 1: List of Tuples (Date + Types)
Store each date-type pair as a tuple in a list:
categorized_array = list(date_type_map.items()) print(categorized_array) # Output: [('Monday', ['type1', 'type2']), ('Tuesday', ['type1', 'type2', 'type3', 'type4']), ...]
Option 2: List of Dictionaries (More Structured)
Use dictionaries to add clarity to each entry:
categorized_array = [{'date': date, 'types': types} for date, types in date_type_map.items()] print(categorized_array) # Output: [{'date': 'Monday', 'types': ['type1', 'type2']}, {'date': 'Tuesday', 'types': ['type1', 'type2', 'type3', 'type4']}, ...]
Option 3: Typed Array (For Strict Data Types)
If you need a strictly typed array (rare for this use case), use Python's array module:
import array # Flatten all types into a single typed array all_types_flat = [] for types in date_type_map.values(): all_types_flat.extend(types) typed_array = array.array('u', all_types_flat) # 'u' for Unicode strings print(typed_array) # Output: array('u', 'type1type2type1type2type3type4...')
内容的提问来源于stack exchange,提问作者Noctious

