I am a huge fan of Ben Marwick. He has so many useful pieces of code for the programming archaeologist or historian!

Edit July 17 1.20 pm: Mea culpa: I originally titled this post, ‘Doing OCR within R’. But, what I’m describing below – that’s not OCR. That’s extracting text from pdfs. It’s very fast and efficient, but it’s not OCR. So, brain fart. But I leave the remainder of the post as it was. For command line OCR (really, actual OCR) on a Mac, see the link to Ben Schmidt’s piece at the bottom. Sorry.

Edit July 17 10 pm: I am now an even bigger fan of Ben’s. He’s updated his script to either a) perform OCR by calling Tesseract from within R or b) grab the text layer from a pdf image. So this post no longer misleads. Thank you Ben!

Object Character Recognition, or OCR, is something that most historians will need to use at some point when working with digital documents. That is, you will often encounter pdf files of texts that you wish to work with in more detail (digitized newspapers, for instance). Often, there is a layer within the pdf image containing the text already: if you can highlight text by clicking and dragging over the image, you can copy and paste the text from the image. But this is often not the case, or worse, you have tens or hundreds or even thousands of documents to examine. There is commercial software that can do this for you, but it can be quite expensive

One way of doing OCR on your own machine with free tools, is to use Ben Marwick’s pdf-2-text-or-csv.r script for the R programming language. Marwick’s script uses R as wrapper for the Xpdf programme from Foolabs. Xpdf is a pdf viewer, much like Adobe Acrobat. Using Xpdf on its own can be quite tricky, so Marwick’s script will feed your pdf files to Xpdf, and have Xpdf perform the text extraction. For OCR, the script acts as a wrapper for Tesseract, which is not an easy piece of software to work with. There’s a final part to Marwick’s script that will pre-process the resulting text files for various kinds of text analysis, but you can ignore that part for now.

  1. Make sure you have R downloaded and installed on your machine (available from http://www.r-project.org/)
  2. Make sure you have Xpdf downloaded and installed (available from ftp://ftp.foolabs.com/pub/xpdf/xpdfbin-win-3.04.zip ). Make a note of where you unzipped it. In particular, you are looking for the location of the file ‘pdftotext.exe’. Also, make sure you know where ‘pdftoppm’ is located too (it’s in that download).
  3. Download and install Tesseract https://code.google.com/p/tesseract-ocr/ 
  4. Download and install Imagemagick http://www.imagemagick.org/
  5. Have a folder with the pdfs you wish to extract text from.
  6. Open R, and paste Marwick’s script into the script editor window.
  7. Make sure you adjust the path for “dest” and the path to “pdftotext.exe” to the correct location
  8. Run the script! But read the script carefully and make sure you run the bits you need. Ben has commented out the code very well, so it should be fairly straightforward.

Obviously, the above is framed for Windows users. For Mac users, the steps are all the same, except that you use the version of Xpdf, Tesseract, and Imagemagick built for IOS, and your paths to the other software are going to be different. And of course you’re using R for Mac, which means the ‘shell’ commands have to be swapped to ‘system’! (As of July 2014, the Xpdf file for Mac that you want is at ftp://ftp.foolabs.com/pub/xpdf/xpdfbin-mac-3.04.tar.gz ) I’m not 100% certain of any other Mac/PC differences in the R script – these should only exist at those points where R is calling on other resources (rather than on R packages). Caveat lector, eh?

The full R script may be found athttps://gist.github.com/benmarwick/11333467. So here is the section that does the text extraction from pdf images (ie, you can copy and highlight text in the pdf):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
###Note: there's some preprocessing that I (sg) haven't shown here: go see the original gist
 
################# Wait! ####################################
# Before proceeding, make sure you have a copy of pdf2text
# on your computer! Details: https://en.wikipedia.org/wiki/Pdftotext
 
# Tell R what folder contains your 1000s of PDFs
dest <- "G:/somehere/with/many/PDFs"
 
# make a vector of PDF file names
myfiles <- list.files(path = dest, pattern = "pdf",  full.names = TRUE)
 
# now there are a few options...
 
############### PDF to TXT #################################
# convert each PDF file that is named in the vector into a text file
# text file is created in the same directory as the PDFs
# note that my pdftotext.exe is in a different location to yours
lapply(myfiles, function(i) system(paste('"C:/Program Files/xpdf/bin64/pdftotext.exe"', paste0('"', i, '"')), wait = FALSE) )
 
# where are the txt files you just made?
dest # in this folder

And here’s the bit that does the OCR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre>
                     ##### Wait! #####
# Before proceeding, make sure you have a copy of Tesseract
# on your computer! Details & download:
# and a copy of ImageMagick: http://www.imagemagick.org/
# and a copy of pdftoppm on your computer!
# And then after installing those three, restart to
# ensure R can find them on your path.
# And note that this process can be quite slow...
 
# PDF filenames can't have spaces in them for these operations
# so let's get rid of the spaces in the filenames
 
sapply(myfiles, FUN = function(i){
  file.rename(from = i, to =  paste0(dirname(i), "/", gsub(" ", "", basename(i))))
})
 
# get the PDF file names without spaces
myfiles <- list.files(path = dest, pattern = "pdf",  full.names = TRUE)
 
# Now we can do the OCR to the renamed PDF files. Don't worry
# if you get messages like 'Config Error: No display
# font for...' it's nothing to worry about
 
lapply(myfiles, function(i){
  # convert pdf to ppm (an image format), using
  shell(shQuote(paste0("pdftoppm ", i, " -f 1 -l 10 -r 600 ocrbook")))
  # convert ppm to tif ready for tesseract
  shell(shQuote(paste0("convert *.ppm ", i, ".tif")))
  # convert tif to text file
  shell(shQuote(paste0("tesseract ", i, ".tif ", i, " -l eng")))
  # delete tif file
  file.remove(paste0(i, ".tif" ))
  })
 
# where are the txt files you just made?
dest # in this folder

Besides showing how to do your own OCR, Marwick’s script shows some of the power of R for doing more than statistics. Mac users might be interested in Ben Schmidt’s tutorial ‘Command-line OCR on a Mac’ from his digital history graduate seminar at Northeastern University, online athttp://benschmidt.org/dighist13/?page_id=129.


출처 : Extracting Text from PDFs; Doing OCR; all within R


바로 : 요즘은 PDF에서 곧장 텍스트를 추출할 수 있다. 그러나 다양한 이유로 텍스트 추출이 어려운 경우가 있다. 물론 이를 지원하는 수 많은 유료소프트웨어가 있기는 하지만......돈 없는 우리가 불법행위를 하지 않으면서 텍스트를 추출하는 방법은 무엇인가?! 저자는 무료툴인 R을 통해서 텍스트를 추출하는 방법에 대해서 서술하고 있다. 



8 월 27일-28일, 고려대학교에서 한국사회연구소 주최로 R Commander 특강이 진행됩니다. 한국사회연구소는 사회과학 연구방법론 분야에서 오랜 교육경험과 고급 연구를 진행해온 기관으로서, 한국 사회과학분야에서 R의 대중화를 위한 KRUG의 노력에 전폭적인 지지를 보내며, 이번 특강 개설을 제안하였습니다.

R의 학습에 부담을 느끼는 사회과학분야의 연구자를 주대상으로 하는 R의 기초 GUI 툴을 활용한 연구방법론 특강입니다. 이번 강의의 내용과 경험을 KRUG 회원들과 공유하겠습니다. 감사합니다.


- 신종화 올림


평소 데이터마이닝에 관심이 있는 분들은 한번 쯤 들어볼 만한 내용으로 생각됩니다.


개인적으로 관심을 가지고 있는 R 인지라 가고 싶지만,수업이 사회과학분야이다보니 본인이 관심을 가지고 있는 분야에 대한 내용이 없을 것 같기도 하고......사실 10만원은 학생입장에서 너무 부담이다. ㅠㅠ 그냥 열심히 자습해야겠다. 어차피 고문헌에 대한 R분석은...분석은...ㅠㅠ



R을 통해서 단일 논문에서 자주 출현하는 키워드를 클라우드로 구현해보았다. 대상 논문은 김현교수님의 "디지털 인문학:인문학과 문화콘텐츠의 상생 구도에 관한 구상[각주:1]"으로 하였다. 만약 어떤 문장에서 자주 출현하는 단어들과 그 빈도수를 시각화하고 싶다면 괜찮은 방법으로 생각된다. 






김현 교수님의 "디지털 인문학:인문학과 문화콘텐츠의 상생 구도에 관한 구상"은 너무나 당연하게도 "인문학"과 "디지털"이 가장 많이 출현하였다. 특히 인문학의 기본에 디지털을 추가한다는 개념과도 같게 "인문학"은 물론이고 "인문"도 자주 출현하는 것을 볼 수 있다. 그 뒤를 "지식"이 따라가고 있다. 재미있는 것은 제목에 출현한 "문화콘텐츠"보다 "인문콘텐츠"의 출현빈도가 더욱 많다는 것이다. "인문콘텐츠"을 강조하고 싶으셨나 보다.


그 뒤를 따르고 있는 단어들은 대부분이 "연구"나 "인력" 혹은 "교육" 및 "육성"등이 자치하고 있다. 이는 본 논문에서 가장 중요시 하는 것이 앞으로 디지털 인문학이 발전하기 위하여 후학들을 어떻게 교육시키고 육성할 것인가에 맞추어져 있다고 할 수 있다.



# 모든 명령어의 세부 내용이 궁금할 때에는 "?file"혹은 "??file"의 형식으로 입력하면 상세한 설명이 당신의 눈앞에 펼쳐진다. 물론 영어 압박이다. 하지만...이쪽 바닥이 원래 꼬브랑말을 할 수 밖에 없다. ~.~;;

# 중간중간 실행결과를 "dh.lines"처럼 입력해서 구동하는 것을 추천한다. 그래야 어떻게 변환됐는지 알 수 있다.

# 본 내용에서는 다음과 같은 팩키지를 사용하게 된다. "KoNLP"는 한글에 관한 텍스트 마이닝(text mining package)의 기본이며 필수라고 생각해도 무방하다. "RColorBrewer"는 시각화시의 색 관련 사항이다. 아름다운 시각화에 관심이 없으면 무시해도 좋다. "wordcloud"는 단어들을 크라우드로 변환해주는 package이다.

# 패키지를 설치한다.

install.packages("KoNLP")
install.packages("RColorBrewer")
install.packages("wordcloud")

# 패키지를 로딩한다.

library(KoNLP)
library(RColorBrewer)
library(wordcloud)

# 한글처리의 경우 "UTF-8"코드로"txt"형식으로 저장이 기본이다.

dh <- file("c:/rtext/dh.txt", encoding="UTF-8")

# 불러온 text에 라인을 넣어주어야 한다.

dh.lines <- readLines(dh)

# 세종단어집을 불러온다. 그런데 세종단어집은 완전하지 않다.

useSejongDic()

# 그래서 "dh.lines"을 실행해서 세종단어집에 포함되지 않은 아래 단어들을 적당히 추가시켰다. 참고로 단어집에 포함되지 않은 단어들은 조사와 붙어서 나오는 경우가 많다.

mergeUserDic(data.frame(c("문화콘텐츠","인문콘텐츠","스토리텔링","코디네이터","콘텐츠"), c("ncn")))

# 이제 라인으로 구획된 text에서 단어만을 추출해준다.

dh.nouns <- sapply(dh.lines, extractNoun, USE.NAMES=F)

# 이제 각각의 단어들이 몇 회 출현하였는지 숫자를 센다. 사실 데이터만으로는 "dh.wordcount"만으로 완성되었다고 볼 수 있다. 남은 건 가시화다.

dh.wordcount <- table(unlist(dh.nouns))

# 예쁘게 꾸미기 옵션이다. 세팅을 바꾸어가면서 색의 변화을 즐겨보자. 본인은 취미 없다.

pal <- brewer.pal(12,"Set3")
pal <- pal[-c(1:2)]

# 이제 실제로 가시화를 한다. 랜덤으로 해놓고 몇 번 실행하면서 마음에 드는 것을 적당히 골라도 되고, 처음부터 철저하게 원하는대로 나오도록 세팅해도 된다. 본인은 렌덤이다.

wordcloud(names(dh.wordcount),freq=dh.wordcount,scale=c(6,0.3),min.freq=10,
          random.order=T,rot.per=.1,colors=pal)


  1. ...본인의 글이 아니어서 함부로 전문을 올리기가 힘들다. 각자 알아서 적당한 소설이나 논문을 대상으로 해보도록-0-;;; [본문으로]

+ Recent posts