Anna Jeanine Anna Jeanine - 8 days ago 6
PHP Question

Read and parse a tab delimited file PHP

I worked out this Python script to read a tab delimited file and place the values where the line starts with

'\t'
in a
array
. The code which I used for this:

import sys
from collections import OrderedDict
import json
import os

file = sys.argv[1]

f = open(file, 'r')
direc = '/dir/to/JSONs/'
fileJSON = sys.argv[1]+'.json'

key1 = OrderedDict()
summary_data = []
full_path = os.path.join(direc,fileJSON)

Read = True
for line in f:
if line.startswith("#"):
Read = True

elif line.startswith('\tC'):
Read= True

elif line.startswith('\t') and Read == True:
summary = line.strip().split('\t')
key1[summary[1]]=int(summary[0])
Read = True

summary_data.append(key1)
data = json.dumps(summary_data)
with open(full_path, 'w') as datafile:
datafile.write(data)
print(data)


The data which I am parsing:

# BUSCO was run in mode: genome

C:98.0%[S:97.0%,D:1.0%],F:0.5%,M:1.5%,n:1440

1411 Complete BUSCOs (C)
1397 Complete and single-copy BUSCOs (S)
14 Complete and duplicated BUSCOs (D)
7 Fragmented BUSCOs (F)
22 Missing BUSCOs (M)
1440 Total BUSCO groups searched


But, I need this code in PHP.. I have managed to open the file in PHP and to read this! Could someone please help me out?

Answer

I didn't get the point of Read variable - it is always True in your code, the last 'elif' statement would be enough. Below is php version of your script

<?php
    $fileName = $argv[1];
    $dir = '/dir/to/JSONs/';
    $fullPath = $dir . $fileName . '.json';

    $data = [];
    $output = fopen($fileName, 'r');
    while (($line = fgets($output)) !== false) {
        if ($line[0] == "\t") {
            $summary = explode("\t", trim($line));
            if (count($summary) > 1) {
                $data[$summary[1]] = (int)$summary[0];
            }
        }
    }

    $strData = json_encode([$data]);
    $input = fopen($fullPath, 'w+');
    fwrite($input, $strData);
    echo $strData;