【问题标题】:Python: How to extract data in text file based on class information from another text file?Python:如何根据来自另一个文本文件的类信息提取文本文件中的数据?
【发布时间】:2015-06-10 07:40:44
【问题描述】:

在这种情况下,有 3 个类,分别由值 0、1 和 2 表示。我想从另一个名为 fileA.txt 的文本文件中提取属于类 1 的信息。我想知道如何使用python解决这个问题。

例如:

class.txt

0
0
1
2
2
1
1

fileA.txt

a=[1,3,2,1]
b=[3,2]
c=[3,2,1]
d=[3,3]
e=[4,5,6]
f=[3,2,3]
g=[2,2]

预期输出:

c=[3,2,1]
f=[3,2,3]
g=[2,2]

谁能帮帮我?

【问题讨论】:

  • 问之前写了一行代码吗?
  • 所以你想从fileA.txt中选择相同的行(按行号)作为class.txt中的行什么是1
  • 是的,我想选择相同的行。
  • 你让我的眼睛心动了,伙计

标签: python extract extraction data-extraction


【解决方案1】:

读取“class.txt”文件并创建类列表:

with open("class.txt", "rt") as f:
    classes = [int(line) for line in f.readlines()]

读取“fileA.txt”文件并创建正确行列表:

with open("fileA.txt", "rt") as f:
    lines = [line for index, line in enumerate(f.readlines()) if classes[index] == 1]

显示结果:

print "".join(lines)

【讨论】:

    【解决方案2】:

    不是 Python 解决方案,但我喜欢它 :)

    $ grep -n "^1$" class.txt | cut -d: -f1 | while read linenumber
    do
      sed -n "${linenumber}p" < fileA.txt
    done
    

    输出:

    c=[3,2,1]
    f=[3,2,3]
    g=[2,2]
    

    使用的工具有:

    【讨论】:

      【解决方案3】:

      这是一种直观的方法

      classes = [l.strip() for l in open("class.txt").readlines()]
      indices = [i for i, x in enumerate(classes) if x == "1"]
      
      with open('fileA.txt') as file:
          for index,line in enumerate(file):
              if(index in indices):
                  print(line)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-15
        • 2021-11-01
        • 2020-11-13
        • 2021-07-08
        • 2023-01-09
        • 1970-01-01
        • 2011-09-14
        • 2020-08-31
        相关资源
        最近更新 更多