【发布时间】:2020-01-30 18:36:46
【问题描述】:
我已经构建了一个函数来从文本条目中删除无关的垃圾。它使用数组切片器。我现在需要协调已被我的清理功能删除的行,以便所有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))
如何计算切片/突变后未显示在行中的行,即:
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。感谢您的考虑。
【问题讨论】: