python - 如何转置特定行并在 unix 或 python 中以以下格式显示数据

标签 python linux

<分区>

我有以下格式的数据。

group_name  group_item_fetch
topic_name  fast_events_breaking
topic_lag  0
topic_name  item_fetch_prod_stage
topic_lag  0
topic_name  related_item_re
topic_lag  1018713
group_name fast_processing_events
topic_name item_fetch_processed
topic_lag 109323

如何得到下面格式的输出文件?

group_name,topic_name,topic_lag
group_item_fetch,fast_events_breaking,0
"",item_fetch_prod_stage,0
"",related_item_re,1018713
fast_processing_events,item_fetch_processed,109323

最佳答案

使用 python 2.7.12,使用 Ubuntu 16.04,我编写了这段代码,它获取一个文件作为输入,打印结果并将其保存在 out.txt 文件中:

import sys

intial_values = []
output = []
file = open('out.txt','w') 

print 'group_name,topic_name,topic_lag'
file.write('group_name,topic_name,topic_lag\n')

for line in sys.stdin:
  intial_values.append(line.split())

is_previous_group = bool
for index, value in enumerate(intial_values):
  if value[0] == 'group_name':
    output.append([
      value[1],
      intial_values[index + 1][1],
      intial_values[index + 2][1]
    ])
    is_previous_group = True
  elif value[0] == 'topic_name':
    if is_previous_group != True:
      output.append([
        '""',
        value[1],
        intial_values[index + 1][1]
      ])
    is_previous_group = False

for value in output:
  print ','.join(value)
  file.write(','.join(value) + '\n')

我用你的例子将输入放在一个名为 in.txt 的文件中:

group_name  group_item_fetch
topic_name  fast_events_breaking
topic_lag  0
topic_name  item_fetch_prod_stage
topic_lag  0
topic_name  related_item_re
topic_lag  1018713
group_name fast_processing_events
topic_name item_fetch_processed
topic_lag 109323

在终端中使用 cat 和 pipe(我将 python 代码称为“filter_rows.py”):

cat in.txt | python filter_rows.py

结果如你所愿:

group_name,topic_name,topic_lag
group_item_fetch,fast_events_breaking,0
"",item_fetch_prod_stage,0
"",related_item_re,1018713
fast_processing_events,item_fetch_processed,109323

完成! ;)

关于python - 如何转置特定行并在 unix 或 python 中以以下格式显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947627/

相关文章:

python - 安装 scikit : gcc-4. 2 未找到,使用 Clang 代替

regex - 如何用awk拆分单列的输出?

linux - TCP ECN源代码

javascript - 使用 Django 和 Python 包含 JavaScript 文件时出现错误

python - 制作条形图来表示 Pandas Series 中出现的次数

python - 在 map 中使用条件和 lambda

终端 Linux 中的 R 工作区

python - 如何在 python statsmodels 中使用 X-13-ARIMA 获得预测

linux - 什么是命令的十六进制版本,它在现实中意味着什么,这是如何完成的

linux - 计算 TCP 重传