简体   繁体   中英

Removing rows that contain certain value and removing odd numbered columns

trying to work with two text files in python. The goal is to firstly, remove all rows that contain a 3 or 4. After this, remove the first 6 columns entirely. I have figured out how to remove the 6 coloumns:

f = open("filename.txt", "r")
g = open("filename1.txt", "w")

for line in f:
    if line.strip():
        g.write("\t".join(line.split()[6:]) + "\n")
f.close()
g.close()

However, I cannot figure out how to remove a row based on a repeating character/occurence (in this case, the digit 3 or 4 appear in a row should remove that row entirely). And then lastly, to remove all odd columns, but not totally remove them. Essentially, remove the odd columns and add them to end the of the text file (a new text file to write to, that is -- everything is being written to the next text file).

lines = [line.strip() for line in open('file.txt')]
nlines=[]
for line in lines:
    if 3 not in map(int,line.split()) and 4 not in map(int,line.split()): nlines.append(line)
for x in nlines:
    y=x.split()
    y=y[1::2]
    print ' '.join(y)

file.txt

3 4 5 6 7 12 34 56
2 5 6 7 8 11 10 7
4 5 6 7 8 44 55 12
33 66 88 99 79 1 2 5

by removing lines containing 3 or 4 and removing odd numbered columns

output

5 7 11 7
66 99 1 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM