gpt4 book ai didi

php - 读取并解析制表符分隔文件 PHP

转载 作者:行者123 更新时间:2023-12-01 03:31:20 24 4
gpt4 key购买 nike

我编写了这个 Python 脚本来读取制表符分隔的文件,并将以 '\t' 开头的行的值放入 array 中。我为此使用的代码:

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)

我正在解析的数据:

# 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

但是,我需要 PHP 中的这段代码..我已经设法在 PHP 中打开该文件并阅读此内容!有人可以帮我吗?

最佳答案

我没有明白 Read 变量的意义 - 它在您的代码中始终为 True,最后一个 '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;

关于php - 读取并解析制表符分隔文件 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com