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

Python文件处理问题:join语句多余换行导致输出格式异常

解决方案

问题根源

你之前的代码大概率是在写入output_keys.txt时,对每个电视剧名单独执行了带换行的写入操作,导致同季的剧名各自占一行。要解决这个问题,核心是把同季的所有剧名用分号连接成单个字符串后,再整行写入文件。

修正后的完整代码

# 获取输入文件名
input_filename = input("请输入文件名:")

# 初始化字典,键为整数类型的季数,值为对应电视剧名列表
season_shows = {}

# 读取并处理输入文件
with open(input_filename, 'r', encoding='utf-8') as input_file:
    lines = input_file.readlines()
    for line in lines:
        # 去除首尾空白(含换行符),跳过空行
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        
        # 分割季数和剧名(假设每行格式为「季数 剧名」,允许季数后带冒号)
        parts = cleaned_line.split(maxsplit=1)
        if len(parts) != 2:
            continue  # 跳过格式错误的行
        
        season_str, show_title = parts
        # 将季数转为整数,避免字符串排序的异常(比如"10"排在"2"前面)
        try:
            season = int(season_str.replace(':', ''))  # 兼容季数带冒号的格式,比如「3: 剧名」
        except ValueError:
            continue  # 跳过非数字季数的行
        
        # 将剧名添加到对应季的列表中
        if season not in season_shows:
            season_shows[season] = []
        season_shows[season].append(show_title)

# 生成output_keys.txt:按键(季数)升序排列,同季剧名用分号分隔
with open('output_keys.txt', 'w', encoding='utf-8') as keys_file:
    # 对季数进行数值排序
    sorted_seasons = sorted(season_shows.keys())
    for season in sorted_seasons:
        # 用分号连接同季所有剧名
        joined_shows = "; ".join(season_shows[season])
        # 整行写入季数和拼接后的剧名
        keys_file.write(f"{season}: {joined_shows}\n")

# 生成output_titles.txt:按电视剧名字母顺序排序输出
all_shows = []
for shows_list in season_shows.values():
    all_shows.extend(shows_list)
# 按字母顺序排序(默认区分大小写,如需忽略大小写可加key=str.lower)
sorted_shows = sorted(all_shows, key=str.lower)
with open('output_titles.txt', 'w', encoding='utf-8') as titles_file:
    for show in sorted_shows:
        titles_file.write(f"{show}\n")

关键改进点

  1. 季数转为整数:避免字符串排序的逻辑错误(比如字符串"10"会排在"2"前面,整数排序则是正确的升序)
  2. 用join拼接剧名:"; ".join(season_shows[season])直接把同季所有剧名合并成一个带分号的字符串,整行写入后就不会出现换行问题
  3. 健壮性处理:跳过空行、格式错误的行,兼容季数带冒号的常见格式
  4. 忽略大小写排序:生成output_titles.txt时加入key=str.lower,确保字母排序的合理性(比如"Breaking Bad"和"better call saul"能按实际字母顺序排列)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:07:49