簡體   English   中英

Emacs:將CSV導入org-mode

[英]Emacs: import a CSV into org-mode

Emacs有一個非常好的擴展名為org-mode。

我希望能夠輕松地將CSV文件加載到組織模式而不會產生明顯的悲痛。 我所能找到的只是表導入或表捕獲,簡單地說,它甚至不能很好地工作。

請注意,我的部分問題是文本字符串,其中包含逗號。 1,2,3,4不同於1,2,3,4“。

是否有一個函數或perl腳本可以運行將csv文件轉換為org-mode格式?

謝謝!

從組織模式手冊:

抄送| 將活動區域轉換為表格。 如果每行包含至少一個TAB字符,則該函數假定材料是制表符分隔的。 如果每行包含逗號,則假定使用逗號分隔值(CSV)。 如果不是,則將行在空白處拆分為字段。 您可以使用前綴參數強制使用特定分隔符:Cu強制CSV,Cu Cu強制TAB和數字參數N表示至少N個連續空格,或者TAB將是分隔符。 如果沒有活動區域,則此命令將創建一個空的Org表。

因此,只需將數據粘貼到組織文件中,選擇它,然后執行Cu Cc |

我假設您要將CSV專門轉換為組織模式 如果情況並非如此,您可能希望在問題中更明確地了解輸出格式。

這樣的事情應該這樣做,或者至少為你提供一個你可以破解的起點:

  #!/usr/bin/perl

  use strict;
  use warnings;

  use Text::CSV;

  my $csv = Text::CSV->new();

  while ( my $line = <DATA> ) {
    if ( $csv->parse( $line )) {
      my $str = join '|' , $csv->fields();
      print "|$str|\n";
    }
  }


  __DATA__
  1,2,3,4
  1,2,"3,4"

看一下:

Ch f org-table-convert-region

我總是轉換csv所以我把它添加到我的.emacs。

(defun org-convert-csv-table (beg end)
  (interactive (list (mark) (point)))
  (org-table-convert-region beg end ",")
  )

(add-hook 'org-mode-hook
      (lambda ()
    (define-key org-mode-map (kbd "<f6>") 'org-convert-csv-table)))

更新

這是另一個考慮引用逗號的函數:

 a,"12,12",b --> a | 12,12 |b

隨時改進它:-)。

(defun org-convert-csv-table (beg end)
  ; convert csv to org-table considering "12,12"
  (interactive (list (point) (mark)))
  (replace-regexp "\\(^\\)\\|\\(\".*?\"\\)\\|," (quote (replace-eval-replacement
                            replace-quote (cond ((equal "^" (match-string 1)) "|")
                                                   ((equal "," (match-string 0)) "|")
                                                   ((match-string 2))) ))  nil  beg end)

試試這個:

;; Insert a file and convert it to an org table
(defun aleblanc/insert-file-as-org-table (filename)
  "Insert a file into the current buffer at point, and convert it to an org table."
  (interactive (list (ido-read-file-name "csv file: ")))
  (let* ((start (point))
    (end (+ start (nth 1 (insert-file-contents filename)))))
    (org-table-convert-region start end)
    ))

這是一個黑客工作,但它的工作原理。

導出CSV文件時,強制每個條目周圍的引號,然后將所有","替換為垂直條。

最后,我創建了一個像這樣的宏:

C-a    ; Beginning-of-line
|      ; Self-insert-char
C-e    ; end-of-line
|      ; Self-insert-char
<down> ; Down one line

(我不是100%肯定,如果|是自我插入字符或不是,所以最好記錄你自己的宏)

點擊表格中間某處的標簽,org-mode正確格式化。 我發現在狹窄的地區更容易做到這一點。

警告:如果您的輸入中有一個垂直條...它可能無法正常工作。 像這樣的情況應該很容易發現,並且相對容易修復。

通常,當將類似文本的內容導入org-mode時,我發現了一些智能宏寫入的組合,而搜索替換是最簡單的方法

我希望有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM