Python: How to extract data in text file based on class information from another text file?
-
In this case there are 3 classes which is represented by the value 0, 1 and 2. I would like to extract information that are belong to class 1 from another text file called fileA.txt. I would like to know how to solve this using python. For example: 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] Expected output: c=[3,2,1] f=[3,2,3] g=[2,2] Can anyone help me?
-
Answer:
Read the "class.txt" file and create list of classes: with open("class.txt", "rt") as f: classes = [int(line) for line in f.readlines()] Read the "fileA.txt" file and create list of correct lines: with open("fileA.txt", "rt") as f: lines = [line for index, line in enumerate(f.readlines()) if classes[index] == 1] Show the result: print "".join(lines)
Xiong89 at Stack Overflow Visit the source
Other answers
Not a Python solution, but I like it :) $ grep -n "^1$" class.txt | cut -d: -f1 | while read linenumber do sed -n "${linenumber}p" < fileA.txt done Output: c=[3,2,1] f=[3,2,3] g=[2,2] Tools used are: http://linux.die.net/man/1/grep http://linux.die.net/man/1/cut http://linux.die.net/man/1/sed
user1907906
Here's intuitive way to do it 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)
Sarit Adhikari
Related Q & A:
- How to extract files from pgp file?Best solution by Super User
- How to extract data from any website?Best solution by Stack Overflow
- How to use hadoop for text file?Best solution by Stack Overflow
- How to extract latest reply text from email and cut out previous messages?Best solution by Stack Overflow
- How to extract a specific text from an image?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.