[英]Extract specific lines from python and format the output
我有一個看起來像這樣的文本文件:
Some text first
First item A
Second item A
Third item A
Some more text
First item B
Second item B
Third item B
More text
我想提取特定的行(示例中的項目 )並將它們保存為具有以下格式的csv文件:
First item A | Second item A | Third item A
First item B | Second item B | Third item B
哪里| 意思是單獨的列。
這是我在Python中的嘗試:我創建一個列表,打開文本文件並遍歷它,然后將包含正確關鍵字的每個項目附加到我的列表中。
import sys
sys.stdout = open('out.csv', 'w')
f = open("input.txt").readlines()
l = []
for line in f:
if("First" in line and not "Some text" in line):
l.append(line.rstrip())
if("Second" in line):
l.append(line.rstrip())
if("Third" in line):
l.append(line.rstrip())
print(l)
作為下一步,我認為我可以在每個“第三項”之后拆分列表,但我開始懷疑有更簡單的方法來解決這個問題。
with open("in.txt") as f:
out = [[]]
for line in f:
# if any line starts with "First","Second" or "Third" append it
if any(line.startswith(x) for x in ("First","Second","Third")):
out[-1].append(line.rstrip())
# if it starts with Third add a new list for next section
if line.startswith("Third"):
out.append([])
for row in out:
print(" | ".join(row))
First item A | Second item A | Third item A
First item B | Second item B | Third item B
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.