[英]How to read complicated .txt file and transform to JSON
我需要從我們的 MRT 掃描儀生成的 txt 文件中提取信息,然后將信息轉換為具有特定結構的 JSON 文件。 該文本文件不是數據文件,而是包含有關該掃描會話的信息的實際文本文件。 任何人都可以讓我走上正確的道路嗎?
下面是部分文件內容的示例。 我更喜歡用 R 來做,但 MATLAB 或 Python 也是可能的。
Example:
Image filter = "system default";
Uniformity correction = "no";
Geometry correction = "default";
IF_info_seperator = 0;
Total scan duration = "09:05.0";
Rel. SNR = 0.752056241;
Act. TR (ms) = "5000";
Act. TE (ms) = "74";
ACQ matrix M x P = "96 x 94";
ACQ voxel MPS (mm) = "2.50 / 2.55 / 2.50";
REC voxel MPS (mm) = "2.50 / 2.50 / 2.50";
Scan percentage (%) = 97.9166641;
在 R 中,使用readLines
、 gsub
和同事。
## read raw lines; don't warn "final line" (might have unwanted side-effects)
txt <- readLines("mri.txt", warn=FALSE)
## replace first `=` with `§` and split there
spl <- strsplit(sub("=", "§", txt), "§")
## expand lengths of list elements to 2 (throws a `NA` in case)
spl <- lapply(spl, `length<-`, 2)
## remove leading/trailing whitespace; make matrix
tmp <- t(sapply(spl, trimws))
## replace `;` or `"` with empty string,
tmp[,2] <- gsub(";|\"", "", tmp[,2])
tmp
# [,1] [,2]
# [1,] "Image filter" "system default"
# [2,] "Uniformity correction" "no"
# [3,] "Geometry correction" "default"
# [4,] "IF_info_seperator" "0"
# [5,] "Total scan duration" "09:05.0"
# [6,] "Rel. SNR" "0.752056241"
# [7,] "Act. TR (ms)" "5000"
# [8,] "Act. TE (ms)" "74"
# [9,] "ACQ matrix M x P" "96 x 94"
# [10,] "ACQ voxel MPS (mm)" "2.50 / 2.55 / 2.50"
# [11,] "REC voxel MPS (mm)" "2.50 / 2.50 / 2.50"
# [12,] "Scan percentage (%)" "97.9166641"
最后是jsonlite::toJSON
。
library(jsonlite)
toJSON(tmp)
[["Image filter","system default"],["Uniformity correction","no"],["Geometry correction","default"],["IF_info_seperator","0"],["Total scan duration","09:05.0"],["Rel. SNR","0.752056241"],["Act. TR (ms)","5000"],["Act. TE (ms)","74"],["ACQ matrix M x P","96 x 94"],["ACQ voxel MPS (mm)","2.50 / 2.55 / 2.50"],["REC voxel MPS (mm)","2.50 / 2.50 / 2.50"],["Scan percentage (%)","97.9166641"]]
當然,您可能需要對此進行微調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.