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

如何使用Python删除文本文件每行指定字符(冒号)前的所有内容

歌词文本处理代码修正

原代码错误点

  • 判断逻辑错误:if separate in readlines 是判断冒号是否存在于存储所有行的列表中,而非当前遍历的单行,判断对象完全错误
  • 变量误用:遍历过程中直接修改存储全部行的readlines变量,将原本的列表类型强制改为字符串类型,完全破坏了原有数据结构
  • 处理逻辑缺失:没有逐行处理并存储结果,也没有处理歌词内容中本身带冒号的场景,容易出现截断错误

修正后代码

import codecs

# 读取原文件内容
with codecs.open("potato.txt", "r", encoding="utf-8") as lyrics:
    readlines = lyrics.readlines()

separate = ':'
processed_lines = []
for line in readlines:
    if separate in line:
        # 仅分割第一个冒号,避免歌词本身带冒号时被误截断,lstrip()用于删除冒号后的前导空格
        processed_line = line.split(separate, 1)[1].lstrip()
        processed_lines.append(processed_line)
    else:
        # 没有冒号的行直接保留原内容
        processed_lines.append(line)

# 写入处理后的内容
with codecs.open("potato.txt", "w", encoding="utf-8") as lyrics:
    lyrics.writelines(processed_lines)

效果验证

按照给出的示例输入,处理后可完全匹配预期输出:

Lady: Oh how to make things fun… → Oh how to make things fun
Doll Girl: Oh how to make things fun? → Oh how to make things fun?
Doll Boy: Oh. How. To make things fun. → Oh. How. To make things fun.

如果不需要删除冒号后的前导空格,删掉lstrip()方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:09:00