Python 重新格式化表每个条目有多个分隔符
我正在mac上工作,我更喜欢用Bash、R或Python3重新格式化 下面是我正在使用的表的一个小示例。该表有数千行,每行的列数可变。此外,该示例包含12个以逗号分隔的值,从Isofrorm_uu开始,但为了可读性,我将其减少为4Python 重新格式化表每个条目有多个分隔符,python,r,bash,Python,R,Bash,我正在mac上工作,我更喜欢用Bash、R或Python3重新格式化 下面是我正在使用的表的一个小示例。该表有数千行,每行的列数可变。此外,该示例包含12个以逗号分隔的值,从Isofrorm_uu开始,但为了可读性,我将其减少为4 ENSMUSG0000001234 2.0 Isoform1_0.9,0.0,0.6,1.3 Isoform2_0.1,0.0,0.0,0.5 ENSMUSG0000005555 1.0 Isoform1_0.5,0.1,0.4,1.0 Isoform2_0.7,0.
ENSMUSG0000001234 2.0 Isoform1_0.9,0.0,0.6,1.3 Isoform2_0.1,0.0,0.0,0.5
ENSMUSG0000005555 1.0 Isoform1_0.5,0.1,0.4,1.0 Isoform2_0.7,0.3,0.0,0.1 Isoform3_0.3,9.9,2.0,3.0
我希望能够搜索并重新格式化以下感兴趣的行。要提取感兴趣的行,我可以使用
grep "ENSMUSG0000001234" ./filename
但我没有足够的经验知道如何通过位置和各种分隔符提取值,并正确组织输出。我认为python可能是最好的工具,但我是python新手
我需要重新格式化的条目如下所示
0.9 0.0 0.6 1.3
0.1 0.0 0.0 0.5
为清楚起见,此字段的行名称和列名如下
IsoformID Cell1 Cell2 Cell3 Cell4
Isoform1 0.9 0.0 0.6 1.3
Isoform2 0.1 0.0 0.0 0.5
非常感谢您的帮助。我看到您首选的解决方案是
Bash
、R
或Python 3
,但这里有一个快速解决您问题的方法,我可以在php
中为您提供
您可以将以下脚本保存到文件中,例如:reformat.php
<?php
$infile = $argv[1];
$handle = fopen($infile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$data = explode(' ', trim($line));
print $data[0] . '-' . $data[1] . "\n";
foreach (array_slice($data, 2) as $row) {
print str_replace(['_', ','], ' ' , $row) . "\n";
}
}
fclose($handle);
} else {
exit("Unable to open file ($finfile)");
}
脚本逐行读取和处理文件。我使用前两个空格分隔的字段作为块标识符。然后我处理行中剩余的字段(array\u slice($data,2)
)
输出:
ENSMUSG0000001234-2.0
Isoform1 0.9 0.0 0.6 1.3
Isoform2 0.1 0.0 0.0 0.5
ENSMUSG0000005555-1.0
Isoform1 0.5 0.1 0.4 1.0
Isoform2 0.7 0.3 0.0 0.1
Isoform3 0.3 9.9 2.0 3.0
更新:
我试图通过使用python
找到实现目标的方法。我提出了以下解决方案
#!/usr/bin/python
with open("input.txt") as f:
for line in f:
row = line.strip().split(' ')
print row[0] + '-' + row[1]
for data in row[2:]:
print data.replace('_', ' ').replace(',', ' ')
这将产生如上所示的相同输出
#!/usr/bin/python
with open("input.txt") as f:
for line in f:
row = line.strip().split(' ')
print row[0] + '-' + row[1]
for data in row[2:]:
print data.replace('_', ' ').replace(',', ' ')