读取并解析以制表符分隔的文件PHP

2024-04-26 02:32:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了这个Python脚本来读取一个以制表符分隔的文件,并将值放在array中的'\t'开头的位置。我用的代码是:

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)

我正在分析的数据:

^{pr2}$

但是,我需要用PHP编写这个代码。。我已经设法在PHP中打开了这个文件并阅读了这个!有人能帮帮我吗?在


Tags: 文件path代码importjsontruereaddata
3条回答

如果要在php中执行此操作,fgetscsv允许您指定分隔符(不仅仅是逗号):

$file_resource = fopen( $file, "r");
fgetcsv($file_resource, 4096, "\t")

Read变量在您的代码中是不必要的,所以我删除了它并替换了一些您可以在控制台上看到结果的内容:

<?php
$file = $argv[1];
$direc = '/dir/to/JSONs/';
$key1 = [];
$summary_data = [];
$full_path = $direc.$file.'.json';
$file_handler = fopen($full_path, 'r');
if($file_handler){
    while(($line = fgets($file_handler)) !== false){
        if($line[0] == "#" || substr($line, 0 , 2) == "\tC" || empty($line) == true){
            echo 'line found : '.$line;
            continue;
        }else{
            $summary = explode("\t", $line);
            echo 'summary : '.print_r($summary,true);
            $key1[str_replace(["\r","\n"], '', $summary[2])] = (int) $summary[1];
        }
    }
}else{
    echo 'Couldn\'t open file.';
    exit();
}
array_push($summary_data, $key1);
$data = json_encode($summary_data);
fclose($file_handler);
file_put_contents($full_path, $data);

我没有理解Read variable的意思-在您的代码中总是这样,最后一个'elif'语句就足够了。下面是脚本的php版本

<?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;

相关问题 更多 >