Class: MyMatrix
- Inherits:
-
Object
- Object
- MyMatrix
- Includes:
- Enumerable
- Defined in:
- lib/mymatrix.rb,
lib/mymatrix/version.rb
Constant Summary collapse
- SEPARATOR =
to_t()の際のセパレータ。
"\t"- VERSION =
"0.1.8"
Instance Attribute Summary collapse
-
#file ⇒ Object
Returns the value of attribute file.
-
#internal_lf ⇒ Object
Returns the value of attribute internal_lf.
-
#mx ⇒ Object
Returns the value of attribute mx.
Class Method Summary collapse
-
.cp932ize(str) ⇒ Object
CP932範囲外の文字コードを変換する関数。ruby1.9の正規表現(鬼車)のため、1.8では使えない。.
- .make_path(path, opts = { }) ⇒ Object
-
.tosjis(str) ⇒ Object
Args str :: UTF8文字列 ====Return CP932の文字列.
-
.toutf8(str) ⇒ Object
- 外部ファイルエンコード(CP932)を内部エンコード(UTF8)に変換する ====Args str
-
CP932 string ====Return UTF8 String.
-
.toUtf8Mac(str) ⇒ Object
MacOSXのファイルシステムで使われるUTF8-Mac(BOMつきUTF)に変換する.
Instance Method Summary collapse
-
#+(other) ⇒ Object
未検証.
- #<<(row) ⇒ Object
- #[](i) ⇒ Object
- #[]=(key, value) ⇒ Object
- #addColumn(header, column) ⇒ Object
-
#addFlg(targetHeader, compareHeader, values, flgValue = '1') ⇒ Object
compareHeaderの値の中に、valuesに書かれた値があったら、targetHeaderにフラグを立てる.
-
#addHeader(key) ⇒ Object
ヘッダを追加する.
-
#addHeaders(aheaders) ⇒ Object
ヘッダを追加する(配列).
- #addRow(row) ⇒ Object
- #concat(mx, opt = {}) ⇒ Object
- #concatCells(headers, colname) ⇒ Object
-
#concatDir(dir) ⇒ Object
フォルダ内ファイルの結合。絶対パスを指定する.
- #concatFile(file, opt = {}) ⇒ Object
-
#correctCityCodes!(colname = '都道府県市区町村コード') ⇒ Object
都道府県市区町村コードの桁そろえ Excelで先頭の0が落ちて桁が変わるため.
- #count(header, value) ⇒ Object
-
#countup(header) ⇒ Object
全件カウントして、[value, count] という配列に格納する.
-
#cutOff(head, num) ⇒ Object
num文字以上の項目をnum文字に丸める.
-
#delEndSp! ⇒ Object
末尾空白の削除.
- #delete(v) ⇒ Object
- #delete_at(pos) ⇒ Object
-
#delete_if ⇒ Object
未検証。「要素を順番にブロックに渡して評価し、その結果が真になった要素を すべて削除します。」.
-
#devide(n) ⇒ Object
n分割した配列を返却する.
-
#divide(splitNum) ⇒ Object
複数に分割されたテキストファイルを出力する.
- #dupRow(row, destmx, destrow, headers) ⇒ Object
- #each ⇒ Object
-
#empty ⇒ Object
行が空(ヘッダはそのまま)のコピーを返却する.
-
#empty! ⇒ Object
selfの行を空にする.
- #empty? ⇒ Boolean
- #fill(rows) ⇒ Object
- #filter(header, value) ⇒ Object
-
#find ⇒ Object
ブロックがTrueになる、配列(参照)を返却するメソッド.
-
#first ⇒ Object
Arrayっぽく使うためのメソッド。内部の@mx.first.
-
#flushCol(colname) ⇒ Object
def concat!(mx) o = self.concat(mx) self = o return self end def concatFile!(file) o = self.concatFile(file) self = o return self end.
-
#getColumn(colName) ⇒ Object
カラムの値を配列で返却する.
-
#getColumns(colNames) ⇒ Object
カラムの値を複数指定して、多次元配列を返却するメソッド。.
- #getColumnsByMatrix(colNames) ⇒ Object
-
#getCrrValue(row, str) ⇒ Object
MyipcMatrixとの互換性のため。getValueのエイリアス.
- #getDoubles(arr) ⇒ Object
-
#getHeaders ⇒ Object
ヘッダのコピーを返却する.
-
#getPath ⇒ Object
読み込んだファイルのパスを返却する.
- #getValue(row, str, offset = 0) ⇒ Object (also: #val)
-
#getValues(colName) ⇒ Object
getColumn のエイリアスメソッド.
-
#index(colName, value) ⇒ Object
colNameの値がvalueの行のうち先頭のものを返却する。todo:名称がよくない。.
-
#initialize(file = nil, opts = {}) ⇒ MyMatrix
constructor
- コンストラクタ ====Args file
-
オープンするファイル。 ====Return 生成されたMyMatrixオブジェクト.
-
#last ⇒ Object
Arrayっぽく使うためのメソッド。内部の@mx.last.
-
#localEncode(v, enc = 's') ⇒ Object
ファイルの中身をSJISにするために使ってる.
-
#makeHash(fromColName, toColName) ⇒ Object
fromColName => toColNameのハッシュを作成する。 fromColNameの値が同じだとtoColNameが上書きされるので使いにくいと思われる。.
-
#makeKey(colname) ⇒ Object
colnameがキーのハッシュを作る。valueはrowの配列。.
- #myescape(cell) ⇒ Object
- #pop ⇒ Object
- #push(var) ⇒ Object
- #pushColumn(header, column) ⇒ Object
-
#replaceHeader(before, after) ⇒ Object
ヘッダを置き換える.
-
#reverse ⇒ Object
未検証.
-
#search(colName, value) ⇒ Object
colnameの値がvalueの行のrowを配列で返却する。todo:名称がよくない。.
-
#searchHeader(str) ⇒ Object
strを含む(/#str/)ヘッダ名を配列で返却する。.
-
#searchIndexes(colName, value) ⇒ Object
colnameの値がvalueの行のもののインデックス値を配列で返却する。todo:名称がよくない。.
-
#select(headers) ⇒ Object
headersに記載の.
-
#setPath(path) ⇒ Object
ファイルパスを設定する。 to_tを引数なしで使うと、設定したパスにファイルが生成される。.
- #setSame(head, headValue, hash) ⇒ Object
-
#setValue(row, str, value, offset = 0) ⇒ Object
def getValues(row, arr) out = [] arr.each do |ele| out << getValue(row, ele) end if(out.size == 0) out = nil end return out end.
- #shift ⇒ Object
- #shiftColumn ⇒ Object
-
#size ⇒ Object
行数を返却する.
- #sortBy(colname, reverse = false) ⇒ Object
-
#to_ary ⇒ Object
配列と引き算とかする際に使われる。.
-
#to_csv(outFile = nil, opts = { }) ⇒ Object
CSV出力する。ダブルクオーテーションやカンマをエスケープする。.
- #to_s ⇒ Object
- #to_s_with_header ⇒ Object
-
#to_t(outFile = nil, opts = {}) ⇒ Object
テキスト出力する。outFileにxlsが指定された場合は、xls出力する。 デフォルトではタブ区切りテキスト。outFileの拡張子を.csvにした場合はカンマ区切りテキスト。 optsに設定できる値: :enc => 文字コード。‘u’:UTF-8, ‘s’:Shift_JISのみ設定可能。デフォルトはShift_JIS(CP932) :separator => テキスト出力するときのセパレータ。 :escape => エスケープするか :remove_empty_row => 空行を削除するか。デフォルトfalse(空行を出力する).
-
#to_t_with(postfix = "out", opts = {}) ⇒ Object
読み込んだファイル名にpostfixを付与してテキストファイル出力する.
-
#to_text(outFile) ⇒ Object
使い方はto_t()を参照。yield。.
-
#to_xls(outFile = nil, opts = { }) ⇒ Object
xlsにて出力する。.
-
#twoByteKana! ⇒ Object
半角カタカナの全角化.
-
#uniq! ⇒ Object
未検証。「要素の重複判定は、Object#eql? により行われます。」www.ruby-lang.org/ja/old-man/html/Array.html#uniq.
- #unshift(var) ⇒ Object
-
#unShiftColumn(header, column) ⇒ Object
使い勝手が良くないので気をつけて使う(todo参照).
-
#with_serial(headerName = 'No.') ⇒ Object
行番号を付与する.
- #without(regexp_or_string) ⇒ Object
Constructor Details
#initialize(file = nil, opts = {}) ⇒ MyMatrix
コンストラクタ
Args
- file
-
オープンするファイル。
Return
生成されたMyMatrixオブジェクト
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/mymatrix.rb', line 30 def initialize(file=nil, opts={}) #内部改行コード。 @internal_lf = '<br>' rnd = rand(9999) i = 0 begin @log = Logger.new("MyMatrix_ERR_#{i}.log") rescue i += 1 retry end @log.level = Logger::DEBUG if(FileIO.filesystem == 's') @file = MyMatrix.toutf8(file.to_s) else @file = file end @mx = LoaderFactory.load(@file, opts) @headers = @mx.shift registerMatrix return self end |
Instance Attribute Details
#file ⇒ Object
Returns the value of attribute file.
20 21 22 |
# File 'lib/mymatrix.rb', line 20 def file @file end |
#internal_lf ⇒ Object
Returns the value of attribute internal_lf.
20 21 22 |
# File 'lib/mymatrix.rb', line 20 def internal_lf @internal_lf end |
#mx ⇒ Object
Returns the value of attribute mx.
20 21 22 |
# File 'lib/mymatrix.rb', line 20 def mx @mx end |
Class Method Details
.cp932ize(str) ⇒ Object
CP932範囲外の文字コードを変換する関数。ruby1.9の正規表現(鬼車)のため、1.8では使えない。
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 |
# File 'lib/mymatrix.rb', line 1000 def self.cp932ize(str) out = str.dup cases = [ #['−', '―'], #MINUS SIGN(U+2212) to FULLWIDTH HYPHEN-MINUS(U+2015)(windows) #↑仕様としては上記が正しいが、運用上MINUS SIGN(U+2212) は FULLWIDTH HYPHEN-MINUS(U+FF0D)に変換する #キー入力時にMacとWindowsで同じ文字コードとなることが望ましいため。 ['〜','~'], #WAVE DASH (U+301C) to FULLWIDTH TILDE(U+FF5E)(windows) ['‖','∥'], #DOUBLE VERTICAL LINE (U+2016, "‖") を PARALLEL TO (U+2225, "∥") に ['—', '―'], #EM DASH (U+2014, "—") を HORIZONTAL BAR (U+2015, "―") に #以下、キー入力を想定した変換。 ['ー', 'ー'], #MacのハイフンF7(google ime)→Windows(googleime):同じ ['ー', 'ー'], #MacのハイフンF8(google ime)→Windows(googleime):同じ ['−', '-'], #MacのハイフンF9[−](google ime)→Windows[-](googleime):違う。MINUS SIGN(U+2212) to FULLWIDTH HYPHEN-MINUS(U+FF0D) ['-', '-'], #MacのハイフンF10(google ime)→Windows(googleime):同じ #ユニコード固有文字:ノーブレークスペース ['[\u00A0]', ' '], #yen ['[\u00A5]', '¥'], # éとè:eの上に´と` ['[\u00E9]', 'e'],['[\u00E8]', 'e'], # todo:よく使う文字(http://www.geocities.jp/laut6/mojibakesetumei/mojibakesetumei2.html より) #spaces ['[\u2000]', ' '],['[\u2001]', ' '],['[\u2002]', ' '],['[\u2003]', ' '],['[\u2004]', ' '],['[\u2005]', ' '],['[\u2006]', ' '],['[\u2007]', ' '],['[\u2008]', ' '],['[\u2009]', ' '],['[\u200A]', ' '],['[\u205F]', ' '], #Japanese Addresses ['鵢崎', 'みさ崎'], ['繫', '繋'], ['萊', '莱'] ] cases.each do |c| out.gsub!(/#{c[0]}/, c[1]) end return out end |
.make_path(path, opts = { }) ⇒ Object
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 |
# File 'lib/mymatrix.rb', line 1091 def self.make_path(path, opts={ }) # opath = makepath(@file, {:ext=>nil, :postfix=>postfix}) dir = File.dirname(path) ext = opts[:ext] ext ||= File.extname(path) postfix = opts[:postfix].to_s basename = File.basename(path, ".*") opath = (FileIO.encodePath("#{dir}/#{basename}_#{postfix}#{ext}")) end |
.tosjis(str) ⇒ Object
Args
- str
-
UTF8文字列
Return
CP932の文字列
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/mymatrix.rb', line 61 def self.tosjis(str) if(RUBY_VERSION =~ /1\.[^9]/) #-xは半角カナを全角にするのを抑止するオプション。 out = NKF.nkf('-W -x -s --cp932', str) else str = MyMatrix.cp932ize(str) begin out = str.encode("Windows-31J") rescue => e p e p str out = str end end return out end |
.toutf8(str) ⇒ Object
外部ファイルエンコード(CP932)を内部エンコード(UTF8)に変換する
Args
- str
-
CP932 string
Return
UTF8 String
82 83 84 85 86 87 88 89 90 |
# File 'lib/mymatrix.rb', line 82 def self.toutf8(str) if(RUBY_VERSION =~ /1\.[^9]/) #入力がShift-jisであるとする。 out = NKF.nkf('-S -x -w --cp932', str) else out = str.encode('UTF-8') end return out end |
.toUtf8Mac(str) ⇒ Object
MacOSXのファイルシステムで使われるUTF8-Mac(BOMつきUTF)に変換する
93 94 95 96 |
# File 'lib/mymatrix.rb', line 93 def self.toUtf8Mac(str) out = str return out end |
Instance Method Details
#+(other) ⇒ Object
未検証
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/mymatrix.rb', line 261 def +(other) out = MyipcMatrix.new othHeaders = other.getHeaders selHeaders = getHeaders selHeaders.each do |header| out.addColumn(header, getColumn(header)) end othHeaders.each do |header| out.addColumn(header, other.getColumn(header)) end return out end |
#<<(row) ⇒ Object
281 282 283 |
# File 'lib/mymatrix.rb', line 281 def <<(row) addRow(row) end |
#[](i) ⇒ Object
252 253 254 |
# File 'lib/mymatrix.rb', line 252 def [](i,j) return @mx[i][j] end |
#[]=(key, value) ⇒ Object
308 309 310 |
# File 'lib/mymatrix.rb', line 308 def []=(key, value) @mx[key] = value end |
#addColumn(header, column) ⇒ Object
278 279 280 |
# File 'lib/mymatrix.rb', line 278 def addColumn(header, column) pushColumn(header, column) end |
#addFlg(targetHeader, compareHeader, values, flgValue = '1') ⇒ Object
compareHeaderの値の中に、valuesに書かれた値があったら、targetHeaderにフラグを立てる
736 737 738 739 740 741 742 743 744 745 746 |
# File 'lib/mymatrix.rb', line 736 def addFlg(targetHeader, compareHeader, values, flgValue='1') compares = getColumn(compareHeader) values.each do|value| i = compares.index(value) if(i) setValue(@mx[i], targetHeader, flgValue) else #raise "VALUE NOT FOUND:#{value}" end end end |
#addHeader(key) ⇒ Object
ヘッダを追加する
594 595 596 |
# File 'lib/mymatrix.rb', line 594 def addHeader(key) addHeaders([key]) end |
#addHeaders(aheaders) ⇒ Object
ヘッダを追加する(配列)
587 588 589 590 591 |
# File 'lib/mymatrix.rb', line 587 def addHeaders(aheaders) @headers.concat(aheaders).uniq! registerMatrix end |
#addRow(row) ⇒ Object
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/mymatrix.rb', line 284 def addRow(row) if(row.class != Array) row = [row] end row.size.times do |i| if(row[i] == nil) row[i] = '' end end headerSize = getHeaders.size rowSize = row.size if(headerSize > rowSize) (headerSize - rowSize).times do |i| row << '' end elsif(rowSize > headerSize) raise("row size error. headerSize:#{headerSize} rowSize:#{rowSize}") end @mx << row.dup end |
#concat(mx, opt = {}) ⇒ Object
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 |
# File 'lib/mymatrix.rb', line 854 def concat(mx, opt={}) notfoundHeaders = [] mx.each do |row| o = [] mx.getHeaders.each do |head| begin self.setValue(o, head, mx.getValue(row, head)) rescue => e #p e if(opt[:loose]==true) self.addHeaders([head]) #p "#{head} added" retry else notfoundHeaders << head end end end self << o end if(notfoundHeaders.size > 0) raise "notfoundHeader : #{notfoundHeaders.uniq.join(',')}" end return self end |
#concatCells(headers, colname) ⇒ Object
687 688 689 690 691 692 693 694 695 696 |
# File 'lib/mymatrix.rb', line 687 def concatCells(headers, colname) addHeaders([colname]) @mx.each do |row| val = [] headers.each do |header| val << getValue(row, header) end setValue(row, colname, val.join('_').gsub(/_+/, '_')) end end |
#concatDir(dir) ⇒ Object
フォルダ内ファイルの結合。絶対パスを指定する
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 |
# File 'lib/mymatrix.rb', line 886 def concatDir(dir) dir = File.(dir) Dir.entries(dir).each do |ent| if(ent =~ /^\./) else #p ent file = dir + '/' + ent #p "concat:#{file}" nmx = MyMatrix.new(file) self.concat(nmx) end end end |
#concatFile(file, opt = {}) ⇒ Object
879 880 881 882 883 884 |
# File 'lib/mymatrix.rb', line 879 def concatFile(file, opt={}) #p file mx = MyMatrix.new(file) self.concat(mx, opt) return self end |
#correctCityCodes!(colname = '都道府県市区町村コード') ⇒ Object
都道府県市区町村コードの桁そろえExcelで先頭の0が落ちて桁が変わるため
950 951 952 953 954 955 956 957 958 959 960 961 962 |
# File 'lib/mymatrix.rb', line 950 def correctCityCodes!(colname = '都道府県市区町村コード') self.each do |row| code = self.val(row, colname) if(code.length == 4) self.setValue(row, colname, sprintf("%05d", code)) elsif(code.length == 5) #correct else raise "Citycode length error. '#{code}'" end end return self end |
#count(header, value) ⇒ Object
797 798 799 800 801 802 803 804 805 806 |
# File 'lib/mymatrix.rb', line 797 def count(header, value) out = 0 arr = getColumn(header) arr.each do |ele| if(ele == value) out += 1 end end return out end |
#countup(header) ⇒ Object
全件カウントして、[value, count] という配列に格納する
808 809 810 811 812 813 814 815 |
# File 'lib/mymatrix.rb', line 808 def countup(header) out = [] values = getColumn(header).uniq values.each do |value| out << [value, self.count(header, value)] end return out end |
#cutOff(head, num) ⇒ Object
num文字以上の項目をnum文字に丸める
1083 1084 1085 1086 1087 1088 1089 1090 |
# File 'lib/mymatrix.rb', line 1083 def cutOff(head, num) self.each do |row| v = self.val(row, head) if(v =~ /(.{#{num}})/) self.setValue(row, head, $1) end end end |
#delEndSp! ⇒ Object
末尾空白の削除
965 966 967 968 969 970 971 972 973 974 975 |
# File 'lib/mymatrix.rb', line 965 def delEndSp! self.each do |row| self.getHeaders.each do |head| val = self.val(row, head) if(val =~ /(.*)[ ]+$/) self.setValue(row, head, $1) end end end return self end |
#delete(v) ⇒ Object
631 632 633 |
# File 'lib/mymatrix.rb', line 631 def delete(v) @mx.delete(v) end |
#delete_at(pos) ⇒ Object
620 621 622 |
# File 'lib/mymatrix.rb', line 620 def delete_at(pos) @mx.delete_at(pos) end |
#delete_if ⇒ Object
未検証。「要素を順番にブロックに渡して評価し、その結果が真になった要素を すべて削除します。」
625 626 627 628 629 630 |
# File 'lib/mymatrix.rb', line 625 def delete_if out = @mx.delete_if do |row| yield(row) end @mx = out end |
#devide(n) ⇒ Object
n分割した配列を返却する
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 |
# File 'lib/mymatrix.rb', line 718 def devide(n) out = [] mx = @mx.dup eleSize = mx.size/n n.times do |i| o = self.empty eleSize.times do |j| o << mx.shift end out << o end #@mx.size%n分余ってるので、追加 mx.each do |ele| out[n-1] << ele end return out end |
#divide(splitNum) ⇒ Object
複数に分割されたテキストファイルを出力する
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
# File 'lib/mymatrix.rb', line 347 def divide(splitNum) lineNum = (@mx.size / splitNum) + 1 mymxs = [] tmp = MyMatrix.new tmp.file = @file tmp.addHeaders(getHeaders) @mx.each_with_index do |row, i| tmp << row.dup if((i+1) % lineNum == 0) mymxs << tmp tmp = MyMatrix.new tmp.addHeaders(getHeaders) tmp.file = @file end end mymxs << tmp mymxs.each_with_index do |mymx, i| p i mymx.to_t_with("#{i}") end end |
#dupRow(row, destmx, destrow, headers) ⇒ Object
932 933 934 935 936 937 938 |
# File 'lib/mymatrix.rb', line 932 def dupRow(row, destmx, destrow, headers) headers.each do |head| val = self.getValue(row, head) destmx.setValue(destrow, head, val) end return destrow end |
#each ⇒ Object
233 234 235 236 237 |
# File 'lib/mymatrix.rb', line 233 def each @mx.each do |row| yield(row) end end |
#empty ⇒ Object
行が空(ヘッダはそのまま)のコピーを返却する
766 767 768 769 770 |
# File 'lib/mymatrix.rb', line 766 def empty out = self.dup out.empty! return out end |
#empty! ⇒ Object
selfの行を空にする
773 774 775 776 |
# File 'lib/mymatrix.rb', line 773 def empty! @mx = [] return self end |
#empty? ⇒ Boolean
1079 1080 1081 |
# File 'lib/mymatrix.rb', line 1079 def empty? @mx.empty? end |
#fill(rows) ⇒ Object
777 778 779 780 781 782 |
# File 'lib/mymatrix.rb', line 777 def fill(rows) rows.each do |row| self << row end return self end |
#filter(header, value) ⇒ Object
824 825 826 827 828 829 830 831 832 833 |
# File 'lib/mymatrix.rb', line 824 def filter(header, value) out = empty @mx.each do|row| v = getValue(row, header) if(v == value) out << row end end return out end |
#find ⇒ Object
ブロックがTrueになる、配列(参照)を返却するメソッド
635 636 637 638 639 640 641 642 643 644 |
# File 'lib/mymatrix.rb', line 635 def find #todo rowsを返却するのと、Mymatrxixを返却するのとどっちがイイのか。。 rows = [] @mx.each do |row| if(yield(row)) rows << row.dup end end return rows end |
#first ⇒ Object
Arrayっぽく使うためのメソッド。内部の@mx.first
1072 1073 1074 |
# File 'lib/mymatrix.rb', line 1072 def first @mx[0] end |
#flushCol(colname) ⇒ Object
def concat!(mx) o = self.concat(mx) self = o return self end def concatFile!(file) o = self.concatFile(file) self = o return self end
913 914 915 916 917 918 |
# File 'lib/mymatrix.rb', line 913 def flushCol(colname) @mx.each do |row| self.setValue(row, colname, '') end return self end |
#getColumn(colName) ⇒ Object
カラムの値を配列で返却する
147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/mymatrix.rb', line 147 def getColumn(colName) out = [] @mx.each do |row| begin out << getValue(row, colName) rescue raise "#{colName} notfound: #{row}" end end return out end |
#getColumns(colNames) ⇒ Object
カラムの値を複数指定して、多次元配列を返却するメソッド。
164 165 166 167 168 169 170 |
# File 'lib/mymatrix.rb', line 164 def getColumns(colNames) out = [] colNames.each do |colName| out << getColumn(colName) end return out end |
#getColumnsByMatrix(colNames) ⇒ Object
173 174 175 176 177 178 179 180 |
# File 'lib/mymatrix.rb', line 173 def getColumnsByMatrix(colNames) out = MyMatrix.new colNames.each do |colName| col = getColumn(colName) out.addColumn(colName, col) end return out end |
#getCrrValue(row, str) ⇒ Object
MyipcMatrixとの互換性のため。getValueのエイリアス
682 683 684 685 |
# File 'lib/mymatrix.rb', line 682 def getCrrValue(row, str) p 'this class is not MyipcMatrix.' getValue(row, str) end |
#getDoubles(arr) ⇒ Object
816 817 818 819 820 821 822 |
# File 'lib/mymatrix.rb', line 816 def getDoubles(arr) doubles = arr.select do |e| arr.index(e) != arr.rindex(e) end doubles.uniq! return doubles end |
#getHeaders ⇒ Object
ヘッダのコピーを返却する
536 537 538 539 |
# File 'lib/mymatrix.rb', line 536 def getHeaders out = @headers.dup return out end |
#getPath ⇒ Object
読み込んだファイルのパスを返却する
699 700 701 |
# File 'lib/mymatrix.rb', line 699 def getPath return @file end |
#getValue(row, str, offset = 0) ⇒ Object Also known as: val
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/mymatrix.rb', line 181 def getValue(row, str, offset = 0) out = nil index = @headerH[str] + offset if(index) out = row[index] #お尻のセルでNULLの場合などは、nilが返却されてしまう。なので、''となるようにする。 if(!out) out = '' end #参照を渡さないためdupする out = out.dup else raise "header not found:#{str} file:#{@file}" end return out end |
#getValues(colName) ⇒ Object
getColumn のエイリアスメソッド
160 161 162 |
# File 'lib/mymatrix.rb', line 160 def getValues(colName) return getColumn(colName) end |
#index(colName, value) ⇒ Object
colNameの値がvalueの行のうち先頭のものを返却する。todo:名称がよくない。
547 548 549 550 551 552 553 554 555 556 557 |
# File 'lib/mymatrix.rb', line 547 def index(colName, value) out = nil col = getColumn(colName) col.each_with_index do |cell, i| if(value == cell) out = i break end end return out end |
#last ⇒ Object
Arrayっぽく使うためのメソッド。内部の@mx.last
1076 1077 1078 |
# File 'lib/mymatrix.rb', line 1076 def last out = @mx[self.size-1] end |
#localEncode(v, enc = 's') ⇒ Object
ファイルの中身をSJISにするために使ってる
369 370 371 372 373 374 375 376 377 378 |
# File 'lib/mymatrix.rb', line 369 def localEncode(v, enc = 's') case enc when 'u' str = MyMatrix.toutf8(v) when 's' str = MyMatrix.tosjis(v) else str = MyMatrix.tosjis(v) end end |
#makeHash(fromColName, toColName) ⇒ Object
fromColName => toColNameのハッシュを作成する。fromColNameの値が同じだとtoColNameが上書きされるので使いにくいと思われる。
658 659 660 661 662 663 664 665 666 |
# File 'lib/mymatrix.rb', line 658 def makeHash(fromColName, toColName) out = Hash.new @mx.each do |row| from = getValue(row, fromColName) to = getValue(row, toColName) out[from] = to end return out end |
#makeKey(colname) ⇒ Object
colnameがキーのハッシュを作る。valueはrowの配列。
669 670 671 672 673 674 675 676 677 678 679 |
# File 'lib/mymatrix.rb', line 669 def makeKey(colname) out = {} self.each do |row| key = self.val(row, colname) if(out[key] == nil) out[key] = [] end out[key] << row end return out end |
#myescape(cell) ⇒ Object
479 480 481 482 483 484 485 486 487 |
# File 'lib/mymatrix.rb', line 479 def myescape(cell) o = cell.to_s.dup o.gsub!(/"/, '""') if o =~ /[",']/ #' o = "\"#{o}\"" end return o end |
#pop ⇒ Object
614 615 616 |
# File 'lib/mymatrix.rb', line 614 def pop return @mx.pop end |
#push(var) ⇒ Object
617 618 619 |
# File 'lib/mymatrix.rb', line 617 def push(var) return @mx.push(var) end |
#pushColumn(header, column) ⇒ Object
312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/mymatrix.rb', line 312 def pushColumn(header, column) colPos = @headers.length @headers << header registerMatrix column.each_with_index do |cell, i| if(@mx[i] == nil) @mx[i] = [] end @mx[i][colPos] = cell end end |
#replaceHeader(before, after) ⇒ Object
ヘッダを置き換える
541 542 543 544 |
# File 'lib/mymatrix.rb', line 541 def replaceHeader(before, after) @headers[@headerH[before]] = after registerMatrix end |
#reverse ⇒ Object
未検証
239 240 241 242 243 244 245 246 |
# File 'lib/mymatrix.rb', line 239 def reverse out = empty @mx.reverse.each do |row| out << row end return out end |
#search(colName, value) ⇒ Object
colnameの値がvalueの行のrowを配列で返却する。todo:名称がよくない。
572 573 574 575 576 577 578 579 580 581 582 583 584 585 |
# File 'lib/mymatrix.rb', line 572 def search(colName, value) indexes = [] col = getColumn(colName) col.each_with_index do |cell, i| if(value == cell) indexes << i end end out = self.empty indexes.each do |index| out << @mx[index] end return out end |
#searchHeader(str) ⇒ Object
strを含む(/#str/)ヘッダ名を配列で返却する。
708 709 710 711 712 713 714 715 |
# File 'lib/mymatrix.rb', line 708 def searchHeader(str) out = [] getHeaders.each do |header| if(header =~ /#{str}/) out << header end end end |
#searchIndexes(colName, value) ⇒ Object
colnameの値がvalueの行のもののインデックス値を配列で返却する。todo:名称がよくない。
560 561 562 563 564 565 566 567 568 569 |
# File 'lib/mymatrix.rb', line 560 def searchIndexes(colName, value) out = [] col = getColumn(colName) col.each_with_index do |cell, i| if(value == cell) out << i end end return out end |
#select(headers) ⇒ Object
headersに記載の
647 648 649 650 651 652 653 654 |
# File 'lib/mymatrix.rb', line 647 def select(headers) out = self.class.new headers.each do |header| out.addColumn(header, getColumn(header)) end out.file = @file return out end |
#setPath(path) ⇒ Object
ファイルパスを設定する。 to_tを引数なしで使うと、設定したパスにファイルが生成される。
703 704 705 |
# File 'lib/mymatrix.rb', line 703 def setPath(path) @file = path end |
#setSame(head, headValue, hash) ⇒ Object
939 940 941 942 943 944 945 946 |
# File 'lib/mymatrix.rb', line 939 def setSame(head, headValue, hash) idxs = self.searchIndexes(head, headValue) idxs.each do |idx| hash.each_pair do |key, value| self.setValue(@mx[idx], key, value) end end end |
#setValue(row, str, value, offset = 0) ⇒ Object
def getValues(row, arr) out = [] arr.each do |ele| out << getValue(row, ele) end if(out.size == 0) out = nil end return out end
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/mymatrix.rb', line 213 def setValue(row, str, value, offset = 0) if(!row) raise 'row is nil' end @headerH[str] ||= addHeaders([str]) index = @headerH[str] + offset #参照先の値も変更できるように、破壊メソッドを使う。row[@headerH[str]] = valueでは、参照先が切り替わってしまうので、値の置き換えにならない。 #findなどで取得したrowに対して処理を行う際に必要な変更。 if(row[index].class == String) row[index].sub!(/^.*$/, value) else #raise('not string error.') #todo 強烈なバグな気もするが、例外を回避し値を代入2010年12月15日 begin row[index] = value.to_s rescue row[index] = '' end end end |
#shift ⇒ Object
608 609 610 |
# File 'lib/mymatrix.rb', line 608 def shift return @mx.shift end |
#shiftColumn ⇒ Object
336 337 338 339 340 341 342 343 344 |
# File 'lib/mymatrix.rb', line 336 def shiftColumn() header = @headers.shift column = [] registerMatrix @mx.each do |row| column << row.shift end return header, column end |
#size ⇒ Object
行数を返却する
599 600 601 |
# File 'lib/mymatrix.rb', line 599 def size return @mx.size end |
#sortBy(colname, reverse = false) ⇒ Object
919 920 921 922 923 924 925 926 927 928 929 930 931 |
# File 'lib/mymatrix.rb', line 919 def sortBy(colname, reverse=false) sortmx = [] self.each do |row| key = self.getValue(row, colname) sortmx << [key, row] end sortmx.sort! self.empty! sortmx.each do |keyrow| self << keyrow[1] end return self end |
#to_ary ⇒ Object
配列と引き算とかする際に使われる。
835 836 837 838 839 840 841 842 |
# File 'lib/mymatrix.rb', line 835 def to_ary arr = [] @mx.each do |row| #arr << row.dup arr << row end return arr end |
#to_csv(outFile = nil, opts = { }) ⇒ Object
CSV出力する。ダブルクオーテーションやカンマをエスケープする。
496 497 498 |
# File 'lib/mymatrix.rb', line 496 def to_csv(outFile=nil, opts={ }) to_t(outFile, opts.merge({:separator=>',', :escape=>true})) end |
#to_s ⇒ Object
843 844 845 846 847 848 849 |
# File 'lib/mymatrix.rb', line 843 def to_s out = '' @mx.each do |row| out = out + row.to_s + "\n" end return out end |
#to_s_with_header ⇒ Object
850 851 852 853 |
# File 'lib/mymatrix.rb', line 850 def to_s_with_header out = self.getHeaders.to_s + "\n" out = out + self.to_s end |
#to_t(outFile = nil, opts = {}) ⇒ Object
テキスト出力する。outFileにxlsが指定された場合は、xls出力する。デフォルトではタブ区切りテキスト。outFileの拡張子を.csvにした場合はカンマ区切りテキスト。optsに設定できる値::enc => 文字コード。‘u’:UTF-8, ‘s’:Shift_JISのみ設定可能。デフォルトはShift_JIS(CP932) :separator => テキスト出力するときのセパレータ。:escape => エスケープするか:remove_empty_row => 空行を削除するか。デフォルトfalse(空行を出力する)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 |
# File 'lib/mymatrix.rb', line 418 def to_t(outFile=nil, opts={}) if(!outFile) outFile = @file end #拡張子の判別 ext = File.extname(outFile).downcase case ext when '.csv' opts[:separator] ||= ',' opts[:escape] ||= true when '.xls' to_xls(outFile) return when '.xlsx' p 'use Tab-Separated-Value text format.' outFile = outFile + '.txt' else #do nothing end #デフォルトオプションの設定 opts[:enc] ||= 's' opts[:escape] ||= false opts[:separator] ||= SEPARATOR to_text(outFile) do |row| orow = [] if(opts[:escape]) row.each do |cell| orow << myescape(cell) end else row.each do |cell| orow << cell.to_s.gsub(/[#{opts[:separator]}\r\n]/, '') end end str = orow.join(opts[:separator]) begin out_str = localEncode(str, opts[:enc]) rescue Encoding::UndefinedConversionError orow.each do |ele| begin localEncode(ele, opts[:enc]) rescue raise "encode error.#{ele}\n(#{orow})" end end @log.debug(row.join(opts[:separator])) end if(opts[:remove_empty_row]) empty_str = localEncode(Array.new(row.size, '').join(opts[:separator]),opts[:enc]) if(empty_str == out_str) out_str = nil end end out_str end end |
#to_t_with(postfix = "out", opts = {}) ⇒ Object
読み込んだファイル名にpostfixを付与してテキストファイル出力する
489 490 491 492 493 |
# File 'lib/mymatrix.rb', line 489 def to_t_with(postfix="out", opts={}) opath = MyMatrix.make_path(@file, {:ext=>nil, :postfix=>postfix}) to_t(opath, opts) return opath end |
#to_text(outFile) ⇒ Object
使い方はto_t()を参照。yield。
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'lib/mymatrix.rb', line 380 def to_text(outFile) outFile = FileIO.encodePath(outFile) out = [] out << @headers @mx.each do |row| out << row end begin fo = open(outFile, 'wb') rescue => e p "cannot write file...#{outFile}" p e sleep(5) retry end out.each_with_index do |row, i| if(row == nil) warn("line #{i} is nil") fo.print("") else str = yield(row) if(str) fo.print(str) else next end end fo.print("\r\n") end fo.close end |
#to_xls(outFile = nil, opts = { }) ⇒ Object
xlsにて出力する。
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 |
# File 'lib/mymatrix.rb', line 501 def to_xls(outFile=nil, opts={ }) default_sheet_name = 'Sheet1' if(outFile =~ /.xls$/) else raise "output file is not xls. set .xls file" end infile =opts[:template] inFile ||= self.file begin xl = Spreadsheet.open(inFile) sheet_str = opts[:sheet] sheet_str ||= default_sheet_name sheet = xl.worksheet(sheet_str) rescue xl = Spreadsheet::Workbook.new sheet = book.create_worksheet sheet.name = default_sheet_name end @headers.each_with_index do |head, i| sheet[0, i] = head end self.each_with_index do |row, i| n = i+1 # line number row.each_with_index do |cell, j| sheet[n, j] = cell end end xl.write(outFile) end |
#twoByteKana! ⇒ Object
半角カタカナの全角化
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 |
# File 'lib/mymatrix.rb', line 977 def twoByteKana! self.each do |row| self.getHeaders.each do |head| val = self.val(row, head) #if(val =~ /[-~]/) if(val =~ /[-]/) #p "#{self.file} #{val}" next end #nval = Kconv.kconv(val, Kconv::UTF8, Kconv::UTF8) #nval = NKF.nkf('-W -w -x --cp932', val) nval = NKF.nkf('-W -w', val) if(val!=nval) #p "#{val}=>#{nval}" end self.setValue(row, head, nval) end end return self end |
#uniq! ⇒ Object
未検証。「要素の重複判定は、Object#eql? により行われます。」www.ruby-lang.org/ja/old-man/html/Array.html#uniq
604 605 606 |
# File 'lib/mymatrix.rb', line 604 def uniq! @mx.uniq! end |
#unshift(var) ⇒ Object
611 612 613 |
# File 'lib/mymatrix.rb', line 611 def unshift(var) return @mx.unshift(var) end |
#unShiftColumn(header, column) ⇒ Object
使い勝手が良くないので気をつけて使う(todo参照)
324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/mymatrix.rb', line 324 def unShiftColumn(header, column) @headers.unshift(header) registerMatrix column.each_with_index do |cell, i| if(@mx[i] == nil) @mx[i] = [] end #todo:ヘッダよりでかいrowがある場合バグる。期待していない一番右の値が取れてしまう。 @mx[i].unshift(cell) end end |
#with_serial(headerName = 'No.') ⇒ Object
行番号を付与する
785 786 787 788 789 790 791 792 793 794 |
# File 'lib/mymatrix.rb', line 785 def with_serial(headerName = 'No.') out = self.empty out.addHeaders([headerName], 1) self.each_with_index do |row, i| no = i + 1 newRow = [no].concat(row) out << newRow end return out end |
#without(regexp_or_string) ⇒ Object
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 |
# File 'lib/mymatrix.rb', line 748 def without(regexp_or_string) if(regexp_or_string.class == String) regexp = /#{regexp_or_string}/ else regexp = regexp_or_string end newHeaders = [] @headers.each do |header| if(header =~ regexp) else newHeaders << header end end out = select(newHeaders) return out end |