You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改TXT遍历代码适配组名前置格式并修复尾行问题

Fixing Your Grouped Data Parser: Reverse Format & Edge Case Handling

Let's sort out this parser step by step. Your original code had two main issues: it relied on a trailing blank line to save the last group, and it was built for group names coming after the data lines instead of before. Here's a revised solution that addresses both problems, plus cleaner line handling.

First, Let's Clarify the New Input Format

Since you need group names to come before their associated data lines, your input should look like this (adjusted from your example):

1
grupa12
239.0.1.122,kanal6
239.0.1.116,kanal7
1.5,kanal8
4.5,kanal9
grupa123
239.0.1.119,kanal10
239.0.1.112,kanal11
4.5,KANAL112
4.0,KANAL123
1.5,KANAL134
grupa1234

Revised Code

from itertools import islice

def parse_mcast_data(file_path):
    MCAST_GROUPS = []
    current_group = None
    current_addresses = []
    current_values = []
    current_names = []
    
    with open(file_path, "r") as filestream:
        # Read the first line as scanTime
        first_line = next(islice(filestream, 0, 1)).strip()
        scanTime = int(first_line)
        
        for line in filestream:
            line = line.strip()
            if not line:  # Skip blank lines entirely
                continue
            
            if line.startswith("grupa"):
                # Save the previous group if we have one
                if current_group is not None:
                    MCAST_GROUPS.append([
                        current_group,
                        current_addresses.copy(),
                        current_values.copy(),
                        current_names.copy()
                    ])
                # Start a new group
                current_group = line
                current_addresses = []
                current_values = []
                current_names = []
            else:
                # Split data line into parts (handle cases where comma might have spaces?)
                parts = line.split(",")
                if len(parts) != 2:
                    continue  # Skip malformed lines
                
                value_or_addr, name = parts
                name = name.strip()
                
                # Check if it's an IP address (>=2 dots) or a numeric value (<=1 dot)
                dot_count = value_or_addr.count(".")
                if dot_count >= 2:
                    current_addresses.append(value_or_addr.strip())
                else:
                    # Try to convert to float (handles integers like "1" too)
                    try:
                        num_val = float(value_or_addr.strip())
                        current_values.append(num_val)
                    except ValueError:
                        # If it's neither IP nor numeric, skip or log?
                        continue
                current_names.append(name)
        
        # Save the last group after loop ends (no trailing blank line needed!)
        if current_group is not None:
            MCAST_GROUPS.append([
                current_group,
                current_addresses,
                current_values,
                current_names
            ])
    
    return MCAST_GROUPS, scanTime

# Example usage
groups, scan_time = parse_mcast_data("INPUT_DATA_SIMULATION.txt")
print(f"Scan Time: {scan_time}")
for group in groups:
    print(f"\nGroup: {group[0]}")
    print(f"Addresses: {group[1]}")
    print(f"Values: {group[2]}")
    print(f"Names: {group[3]}")

Key Improvements Explained

  • Reverse Format Support: We now detect grupa lines first, start a new group, then collect all subsequent data lines until the next grupa line.
  • No Trailing Blank Line Required: After the loop finishes, we check if there's an unsaved group and add it—this fixes the original issue where the last group wouldn't save without a blank line.
  • Cleaner Line Handling: Using strip() removes leading/trailing whitespace (including \n) from every line, so we don't have to manually slice [:-1] or check for \n in strings. Blank lines are skipped entirely.
  • Robust Data Classification: Instead of counting dots manually with a loop, we use count(".") for simplicity. We also add a try/except block to safely convert numeric values, which handles edge cases like integers (e.g., "1" instead of "1.0").
  • Avoids Global Variables: All group-related lists are initialized inside the function and scoped properly, preventing unexpected state leaks between function calls.
  • Malformed Line Handling: The code skips lines that don't split into exactly two parts, making it more resilient to bad input.

内容的提问来源于stack exchange,提问作者kaszankabanka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:09:01