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

文本文件排序与格式化技术求助:读取、合并及数组生成问题

问题与解决方案

需求

  • 从文本中读取内容至指定字符串结束
  • 将被换行拆分的字符串合并为完整一行(尝试过strip()未解决)
  • 根据给定文本生成两个独立任务数组

原始文本

Cat Chores
Get 
cat food.
Dog Chores
Get
dog food. Walk Dog.

格式化后期望效果

Cat Chores
Get cat food.
Dog Chores
Get dog food. Walk Dog.

最终目标输出

cat_chores = ["Get cat food."]
dog_chores = ["Get dog food.", "Walk Dog"]

现有代码(存在逻辑错误)

# Remove whitespace and reformat the file
with open('chores.txt',"r") as f:
  text = input.read()
  text = [lines.strip() for lines in text] 

with open('chores.txt',"w") as f:
  f.writelines(text)
  f.close

# Re-open the file to create the arrays.
with open('chores.txt',"r") as f:
  text = input.read()

if "Cat Chores" in text:
  print (line,end='')
  print(next(input),end='')

if "Dog Chores" in text:
  print (line,end='')
  print(next(input),end='')

修正后的代码与实现说明

完整代码

# 读取文件并按行处理,保留换行外的格式
with open('chores.txt', 'r') as f:
    lines = [line.rstrip('\n') for line in f]

cat_tasks = []
dog_tasks = []
current_group = None

# 遍历行,划分任务组并合并拆分的行
for line in lines:
    stripped_line = line.strip()
    # 跳过空行
    if not stripped_line:
        continue
    # 切换任务分组
    if stripped_line == "Cat Chores":
        current_group = cat_tasks
        continue
    elif stripped_line == "Dog Chores":
        current_group = dog_tasks
        continue
    # 合并被换行拆分的内容:如果当前组最后一项是未完成的开头(比如"Get "),则追加当前行
    if current_group and current_group[-1].endswith(' '):
        current_group[-1] += stripped_line
    else:
        current_group.append(stripped_line + ' ')  # 加空格标记待合并

# 处理任务行:去除多余空格,拆分多任务内容
def parse_tasks(task_list):
    result = []
    for item in task_list:
        clean_item = item.strip()
        # 拆分包含多个任务的行
        if '. ' in clean_item:
            parts = [part.strip() for part in clean_item.split('. ')]
            # 给拆分后的任务补全句号(如果缺失)
            result.extend([part + '.' if not part.endswith('.') else part for part in parts])
        else:
            result.append(clean_item)
    return result

cat_chores = parse_tasks(cat_tasks)
dog_chores = parse_tasks(dog_tasks)

# 输出最终结果
print(f"cat_chores = {cat_chores}")
print(f"dog_chores = {dog_chores}")

各需求实现说明

  1. 按指定字符串划分内容:遍历每行时,通过判断"Cat Chores"和"Dog Chores"两个标记,切换当前处理的任务组,自动停止当前组的读取,直到遇到下一个标记或文件结束。
  2. 合并换行拆分的字符串:不再仅用strip()去空格,而是通过给未完成的任务开头(比如"Get ")添加空格标记,后续行直接追加到该标记的内容后,实现换行内容的合并。
  3. 生成独立任务数组:先整理好每个任务组的内容,再对包含多个任务的行(比如"Get dog food. Walk Dog.")按. 拆分,将每个任务单独存入数组,最终得到目标格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:55:40