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

如何将字符串连续出现的内容拆分到独立TXT文件?

Fixing the Segmented Animal String Storage Issue

Got it, let's sort out this problem! Your current code treats the entire line as a single chunk and dumps all "chicken" instances into one file, which misses the key requirement: splitting up consecutive groups of animals and saving each group to its own dedicated file. Here's how to fix this step by step:

First, Let's Break Down the Core Issue

Your test.txt has a single line of space-separated animal words. The original code doesn't split the line into individual words or track when the animal type changes—so it can't tell the difference between the first two chickens and the last three. That's why all chickens end up in one file.

Working Solution Code

# Read and parse the input file
with open("test.txt", "r") as input_file:
    # Strip extra whitespace and split into individual animal words
    animal_words = input_file.read().strip().split()

# Group consecutive identical animals
animal_groups = []
if animal_words:
    current_group = [animal_words[0]]
    for word in animal_words[1:]:
        if word == current_group[-1]:
            current_group.append(word)
        else:
            animal_groups.append(current_group)
            current_group = [word]
    # Don't forget to add the last group to the list
    animal_groups.append(current_group)

# Map each group to the correct output file (order matters!)
group_to_file = [
    (1, "chicken", 2),
    (2, "duck", 3),
    (3, "parrot", 2),
    (4, "chicken", 3)
]

# Write each group to its corresponding file
for group_index, (file_num, target_animal, target_count) in enumerate(group_to_file):
    try:
        current_group = animal_groups[group_index]
        # Optional validation to ensure groups match expectations
        if current_group[0] == target_animal and len(current_group) == target_count:
            with open(f"{file_num}.txt", "w") as output_file:
                # Join the group back into a space-separated string to match original format
                output_file.write(" ".join(current_group) + "\n")
        else:
            print(f"Warning: Group {group_index+1} doesn't match expected {target_count} {target_animal}s")
    except IndexError:
        print(f"Error: Not enough animal groups found for file {file_num}.txt")

What This Code Does

  1. Parse the Input: Reads test.txt, strips extra whitespace, and splits the content into a list of individual animal words (e.g., ["chicken", "chicken", "duck", ...]).
  2. Group Consecutive Animals: Iterates through the word list, building groups of identical consecutive animals. This gives us a structured list like [["chicken", "chicken"], ["duck", "duck", "duck"], ...].
  3. Map Groups to Files: Uses a predefined list to match each group to the correct output file (1.txt to 4.txt). It validates each group matches the expected animal and count, then writes the group as a space-separated string to the file.

Why Your Original Code Failed

Your code read the entire line as one string and checked if "chicken" was present—so every time it found "chicken" in the line, it wrote the whole line to chicken.txt. It never split the line into individual words or tracked when the animal type switched, so it couldn't separate the two distinct chicken groups.

内容的提问来源于stack exchange,提问作者Izzat Z.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:03:51