用D解析文件

时间:2012-01-24 19:19:08

标签: parsing d dmd

我是D的新手,想要解析形式的生物文件

>name1
acgcgcagagatatagctagatcg
aagctctgctcgcgct
>name2
acgggggcttgctagctcgatagatcga
agctctctttctccttcttcttctagagaga
>name2
gag ggagag

这样我就可以使用相应的'序列'数据捕获'header'name1,name2,name3,..acgcg ...... stuff。

现在我有了这个。但它只会逐行迭代,

import std.stdio;
import std.stream;
import std.regex;


int main(string[] args){
  auto filename = args[1];
  auto entry_name = regex(r"^>(.*)"); //captures header only
  auto fasta_regex = regex(r"(\>.+\n)([^\>]+\n)"); //captures header and correponding sequence

  try {
    Stream file = new BufferedFile(filename);
    foreach(ulong n, char[] line; file) {
      auto name_capture = match(line,entry_name);
      writeln(name_capture.captures[1]);
    }

    file.close();
  }
  catch (FileException xy){
    writefln("Error reading the file: ");
  }

  catch (Exception xx){
    writefln("Exception occured: " ~ xx.toString());
  }
  return 0;
}

我想知道一种提取标题和序列数据的好方法,这样我就可以创建一个关联数组,其中每个项目对应于文件中的一个条目

[name1:acgcgcagagatatagctagatcgaagctctgctcgcgct,name2:acgggggcttgctagctcgatagatcgaagctctctttctccttcttcttctagagaga,.....]

2 个答案:

答案 0 :(得分:8)

标题在它自己的行上吗?所以为什么不检查它并使用appender来分配值

auto current = std.array.appender!(char[]);
string name;
foreach(ulong n, char[] line; file) {
      auto entry = match(line,entry_name);
      if(entry){//we are in a header line

          if(name){//write what was caught 
              map[name]=current.data.dup;//dup because .current.data is reused
          }
          name = entry.hit.idup;
          current.clear();
      }else{
          current.put(line);
      }
}
map[name]=current.data.dup;//remember last capture

地图是您存储值的地方(string[string]将会这样做)

答案 1 :(得分:5)

这是我没有正则表达式的解决方案(我不相信这么简单的输入我们需要regexp):

import std.stdio;
import std.stream;

int main(string[] args) {
  int ret = 0;
  string fileName = args[1];
  string header;
  char[] sequence;
  string[string] content;
  try {  
    auto file = new BufferedFile(fileName);
    foreach(ulong lineNumber, char[] line; file) {
      if (line[0] == '>') {       
        if (header.length > 0) {
          content[header] = sequence.idup;
          sequence.length = 0;
        } // if
        // we have a new header, and new sequence will start after it
        header = line[1..$].idup;
        content[header] = "";
      } else {
          sequence ~= line;
      } // else
    } // foreach
    content[header] = sequence.idup;
    file.close();
  }
  catch (OpenException oe){
    writefln("Error opening file: " ~ oe.toString());
  }
  catch (Exception e){
    writefln("Exception: " ~ e.toString());
  }
  writeln(content);
  return ret;
} // main() function

/+ -------------------------- BEGIN OUTPUT ------------------------------- +
["name3":"gag ggagag", "name1":"acgcgcagagatatagctagatcgaagctctgctcgcgct", "name2":"acgggggcttgctagctcgatagatcgaagctctctttctccttcttcttctagagaga"]
 + -------------------------- END OUTPUT --------------------------------- +/