V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Canglin
V2EX  ›  Python

Python 疑问

  •  
  •   Canglin · 36 天前 · 1038 次点击
    这是一个创建于 36 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python 新手的一个小疑问:
    with open(m4s_file_path, '+rb') as f:
    file_read_cache = 1 * 1024 * 1024
    file_size = f.seek(0, 2)
    file_size = f.tell()
    f.seek(0)
    file = f.read(32)
    if file[0:9] == b'000000000':
    orglen = len(file)
    file = re.sub(b'000000000|avc1', b'', file)
    file = re.sub(b'$', b' ', file)

    remove_orglen = orglen - len(file)
    f.seek(32)
    tail = f.read()
    f.seek(0)
    f.write(file + tail)
    f.truncate(len(file) + len(tail) - remove_orglen)

    sub_file = file[9:]
    f.seek(0)
    f.write(sub_file)

    for i in range(file_read_cache, file_size,
    file_read_cache):
    chunks = f.read(file_read_cache)
    f.seek(i)
    f.write(chunks)

    f.truncate(file_size - 9)
    else:
    pass
    这是我写的一个小 Demo ,但是不知道为什么生成的合并文件种 file 与 tail 中间会有一个空格呢,该如何处理这个呢?
    7 条回复    2024-03-22 15:34:09 +08:00
    clino
        1
    clino  
       36 天前
    贴给智谱清言给的回答:

    在你的代码中,出现空格的原因是你在使用 re.sub 函数替换内容时,将 $ 字符替换为了空格 b' '。在正则表达式中,$ 是一个特殊字符,代表字符串的末尾。所以当 re.sub 函数看到 $ 时,它会查找字符串的末尾并进行替换。
    这里有一个小错误,你可能想要替换的是 b'000000000' 而不是 b'000000000|$'。让我们来修正这部分代码:

    后面还给了三个问题的建议修复代码示例
    channg
        2
    channg  
       36 天前
    问 chatgpt 一下就给你回答了

    file = re.sub(b'$', b' ', file)
    这里,你的目的是在 file 的末尾添加一个空格,但实际上这会在每次处理时添加一个空格到处理过的内容里。由于你在后续的操作中又将 file 写回了文件,这就导致了你观察到的现象。

    但是我不知道回答的对不对
    Canglin
        3
    Canglin  
    OP
       36 天前
    @clino #1 我的目的是想将字符流种的 000000000 与 avcl 删除掉,然后将$字符换成空格,按您的意思我是不是应该将 file = re.sub(b'$', b' ', file)改为 file = re.sub(b'\$', b' ', file)?
    Canglin
        4
    Canglin  
    OP
       36 天前
    @channg #2 我是按照 Claude 写的,困难
    araraloren
        5
    araraloren  
       36 天前
    I can't answer you because the codes are encrypted.
    noahlias
        6
    noahlias  
       36 天前
    我记得发帖的时候可以用 markdown 你这格式看着难受
    Canglin
        7
    Canglin  
    OP
       36 天前
    @noahlias #6 可能是我浏览器的事情,我选的 MD ,但是不知道为什么出来是这个格式
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3023 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 13:35 · PVG 21:35 · LAX 06:35 · JFK 09:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.