从代码块的结果创建组织表

问题描述 投票:1回答:2

我正在尝试根据使用“;”的CSV文件的内容创建一个组织表作为分隔符。

我认为有一个源代码块可以很容易地“捕获”文件的内容,然后将结果传递给创建表的函数,但我卡住了:我找不到使用“结果“第一个源代码块。我知道的函数(org-table-convert-region)期望一个区域可以工作,我不知道如何将“cat”-ed文本作为区域传递。

#+NAME: csvraw
#+BEGIN_SRC sh :results raw
  cat afile.csv
#+END_SRC

感谢您帮助生成一个代码块,该代码块从我的csv文件中生成一个org-table,其中包含如下行:

ID;Region;SubRegion;Area;No
1234;Asia;India;45;2
24251;Europe;Romania;456;67
emacs org-mode org-babel
2个回答
1
投票
(defun jea-convert-csv-to-org-table (fname)
  (interactive "fCSV to convert: ")
  (let ((result '("|-\n")))
    (with-temp-buffer
      (save-excursion (insert-file-contents-literally fname))
      (while (and (not (eobp)) (re-search-forward "^\\(.+\\)$" nil t nil))
        (push (concat "|" (replace-regexp-in-string ";" "|" (match-string 1)) "|\n")
              result))
      (push '"|-\n" result))
    (concat (seq-mapcat #'identity (reverse result)))))

在你的〜/ .emacs文件中安装elisp代码并重启emacs。或者,更好的是,eval它存在(CTRL + x,CTRL + e或ALT + x eval-last-sexp)。

#+NAME: csvraw
#+BEGIN_SRC elisp :results raw
  (jea-convert-csv-to-org-table "/Users/jamesanderson/Downloads/test1.csv")
#+END_SRC

请注意上面elispsh的更改。这是它的行动的GIF:emacs converting csv to org table

代码没有针对大文件进行优化,坦率地说,很快就被抛到了一起。但是,经过一小段测试后,似乎有效。


3
投票

org-table-convert-region(绑定到C-c |)可以相当简单地进行转换。唯一的技巧是指定;作为分隔符。您可以通过使用正确的前缀参数调用它来执行此操作 - 文档字符串说:

(org-table-convert-region BEG0 END0 &optional SEPARATOR)

Convert region to a table.

The region goes from BEG0 to END0, but these borders will be moved
slightly, to make sure a beginning of line in the first line is included.

SEPARATOR specifies the field separator in the lines.  It can have the
following values:

(4)     Use the comma as a field separator
(16)    Use a TAB as field separator
(64)    Prompt for a regular expression as field separator
integer  When a number, use that many spaces, or a TAB, as field separator
regexp   When a regular expression, use it to match the separator
nil      When nil, the command tries to be smart and figure out the
         separator in the following way:
         - when each line contains a TAB, assume TAB-separated material
         - when each line contains a comma, assume CSV material
         - else, assume one or more SPACE characters as separator.

(64)值连续只有三个C-u,因此过程如下:

  • 使用C-x i插入CSV文件。
  • C-x C-x将插入的内容标记为活动区域。
  • C-u C-u C-u C-c | ; RET

什么更酷,在第一行和其余行之间的CSV文件中留空行,将使第一行自动成为表中的标题。

你也可以把它包装在一个代码块中:

#+begin_src elisp :var file="/tmp/foo.csv" :results raw
  (defun csv-to-table (file)
    (with-temp-buffer
      (erase-buffer)
      (insert-file file)
      (org-table-convert-region (point-min) (point-max) ";")
      (buffer-string)))

  (csv-to-table file)
#+end_src

#+RESULTS:
| a | b | c |
|---+---+---|
| d | e | f |
| g | h | i |
© www.soinside.com 2019 - 2024. All rights reserved.