2017-03-25 10 views
0

私はいくつかのデータを抽出して構造化された形式にする必要がある非構造化テキストファイルを持っています。データは次のようになります(各レコードは複数の行に展開されます)このコードを変更して日付を新しい列に含めるにはどうすればよいですか?

21 3月2017 23:10:45テキスト21 3月2017 23:10:45その他のテキスト... ... 21 3月2017 23:10:45そして複数のテキスト2017年3月21日23時10分45秒いくつかのより多くのテキストメッセージ:よりテキスト1テキスト2より多くのテキスト3以上text4

2017年3月22日23時10分45秒のテキスト2017年3月22日23時10分45秒以上のテキスト...。 。23 March 2017 23:10:45その他のテキスト23 3月2017 23:10:45もう少しのテキストメッセージ: more text1 more text2 more text3 more text4

以下のコードは、別の列( "text1"以上、 "text2"、 "text3"、 "text4")で "Message"という単語を入力します。私はという単語を "メッセージ"という単語の直前に含めるように修正したいと思います。ここで私が持っているコードは次のとおりです。

#Read data 
m <- SReadLines("C:/user...", SkipNull=TRUE) 

#reomve special characters that might affect reading the data later: 
m <- sapply(m, function(i) { 
b <- gsub("\032"," ",i) 
gsub("\t","",b) 
}) 

#convert to one big character string 
m <- paste(m, collapse="") 

#since some entries expand on multiple lines, will replace the date 
#(which prepend each piece of information in the file) with a carrot, 
#the replace  new line characters with blanks, then replace carrots 
#with new lines. At the end all texts will on one line: 

date_pattern <- "\\[[0-9]{2}\\-[A-Z]{1}[a-z]{2}\\-[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}" 

m <- gsub(data+pattern, "^", m) 
m <- gsub("\n","",m) 
m <- gsub("\\^", "\n", m) 


#only keep lines with the word "Message" 
m <- a[Grep("Message",m)] 
class(m) <- "character" 
#remove the word "message and trim leading white space: 
m <- sapply(strsplit(m,split = "Message", fixed=TRUE), function(i) (i[2])) 
m <- trimws(m, which="left") 

#write to file: 
writeLines(m, "C:/user...") 

上記のコードの結果は、別の列に単語「メッセージ」(以上テキスト1、テキスト2より、より多くのテキスト3、よりtext4)それぞれの後にすべてです。

私は上記のコードを修正して日付を追加する必要があります。私はそれ自身で日付を抽出し、それをcbindを使って抽出したデータにマージしようとしましたが、1列、2列目、3列目にその日がありました。

答えて

1

ここでは、あなたを助けるかもしれない貪欲なマッチングを利用するいくつかのperlのトリックがあります。

まず(上記のあなたのパターンとは若干異なる。注ヶ月は完全な長さに書き出される)日付パターンを定義するいくつかのデータが

x <- "21 March 2017 23:10:45 text 21 March 2017 23:10:45 More text. 21 March 2017 23:10:45 And more text 21 March 2017 23:10:45 some more text Message: more text1 more text2 more text3 more text4" 

でテストするために取得

date_pattern <- "[0-9]{2} [A-Z]{1}[a-z]+ [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}" 

使用gsubとあなたが欲しいものを得るために後方参照:yiel

gsub(paste0("(.*)(", date_pattern , ")(.*)Message: (.*)"), "\\2 \\4", x) 

DS

"21 March 2017 23:10:45 more text1 more text2 more text3 more text4" 

あなたがより密接に物事を分割したい場合にはgsubからの出力に何かを挿入することができます。

関連する問題