协调数组切片器

Reconciling an array slicer

我已经构建了一个函数来从文本条目中删除多余的垃圾。它使用数组切片器。我现在需要协调已被我的清理功能删除的行,以便所有 lines_lost + lines_kept = 总行。源代码如下:

def header_cleanup(entry_chunk):
    # Removes duplicate headers due to page-continuations
    entry_chunk = entry_chunk.replace("\r\n\r\n","\r\n")
    header = lines[1:5]
    lines[:] = [x for x in lines if not any(header == x for header in headers)]
    lines = headers + lines
    return("\n".join(lines))

如何计算slice/mutation之后未出现的行数,即:

original_length = len(lines)
lines = lines.remove_garbage
garbage = lines.garbage_only_plz
if len(lines) + len(garbage) == original_length:
    print("Good!")
else:
    print("Bad!  ;(")

最终答案看起来像这样:

def header_cleanup(entry_chunk):
    lines = entry_chunk.replace("\r\n\r\n","\r\n")
    line_length = len(lines)
    headers = lines[1:5]
    saved_lines = []
    bad_lines = []
    saved_lines[:] = [x for x in lines if not any(header == x for header in headers)]
    bad_lines[:] = [x for x in lines if any(header == x for header in headers)]
    total_lines = len(saved_lines) + len(bad_lines)
    if total_lines == line_length:
        print("Yay!")
    else:
        print("Boo.")
        print(f"{rando_trace_info}")
        sys.exit()
    final_lines = headers + saved_lines
    return("\n".join(final_lines))

Okokokokok - 我知道你在想:这是多余的,但它是必需的。在解决更多 pythonic 问题后打开编辑。感谢考虑。

不要重复使用 lines 变量,使用不同的变量,这样您就可以从原始行中清除垃圾。

clean_lines = remove_garbage(lines)
garbage = garbage_only(lines)
if len(clean_lines) + len(garbage) == len(lines):
    print("Good!")
else:
    print("Bad!")

您可能希望有一个函数 returns 两者:

clean_lines, garbage = filter_garbage(lines)