2014-11-04 26 views
0

我有一個看起來像這樣從XLSX文件中去掉數據:查找字符

[6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry" 

我想搜索的陣列和前括號返回第二個數字的值。即,搜索Complaint應該返回3。任何幫助表示讚賞。

NB - 根據對數組的註釋更新。刪除了OP中的字符串轉換。

require 'roo' 

today_file=(File.dirname(__FILE__) + '/output/today-report.xlsx') 

def by_value(data, value) 
    found = data.find do |k, v| 
    v == value 
    end 

    found and found[0][1] 
end 

data = Roo::Excelx.new (today_file) 

output = by_value(data, "Complaint").inspect 

puts output 

當運行這個返回「零」

從這個陣列的輸出是這種形式:

{[1, 1]=>"YESTERDAY - 02/10/14", [1, 4]=>"Another comment below the fold - scroll down", [2, 1]=>"Yesterday we received 11 regarding the service.", [4, 1]=>"TYPE", [6, 1]=>"", [6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry", [6, 5]=>"Total (Type)", [7, 1]=>"Editorial and other queries", [7, 2]=>1.0, [7, 3]=>7.0,...} 
+0

數據是哈希還是大格式字符串? – Linuxios 2014-11-04 16:14:26

+1

從字面上看,你的數據結構如何?數組對象作爲鍵的散列?如果是這樣的話,那會很容易......如下所示:'data.key(string)[1]'如果data是該結構而'string'是您要查找的字符串。 – lurker 2014-11-04 16:14:49

+0

如果它更容易,它可能非常容易。它目前是一個轉換爲字符串的散列。 – 2014-11-04 16:16:32

回答

0

這是一個奇怪的要求。這是如何做到這一點。

word = "Complaint" 
data_string[/, (\d+)\]=>"#{Regexp.escape(word)}"/, 1] # => "3" 
+0

聰明而可怕。希望這是最後的手段。要成爲一個通用的解決方案,不要忘記用['Regexp.escape']替代'word'值(http://www.ruby-doc.org/core-2.1.4/ Regexp.html#方法-C-逃逸)。 – tadman 2014-11-04 16:28:31

+0

@tadman謝謝,我忘了那一點。 – sawa 2014-11-04 16:30:34

+0

還有如何處理搜索'煩人'字符串''的問題。 – tadman 2014-11-04 16:33:05

0

如果你是新來的Ruby,你會想花時間熟悉Enumerable庫。它有很多操作和提取數據的工具。

在這種情況下,find這項工作:

def by_value(data, value) 
    # Find the key/value pair where the value matches 
    found = data.find do |k, v| 
    v == value 
    end 

    # If one of these was found, pull the second number from the key 
    found and found[0][1] 
end 

data = {[6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry"} 

puts by_value(data, "Complaint").inspect 
# => 3 

值得一提的是,這是一個相對緩慢的操作,因爲你正在做一個線性搜索。如果這樣做了足夠頻繁你要反轉它使搜索更快:

def by_value(data, value) 
    found = data[value] 

    found and found[1] 
end 

# Using Hash#invert switches the keys and values so you can now look-up by value 
data = {[6, 2]=>"Comment", [6, 3]=>"Complaint", [6, 4]=>"Enquiry"}.invert 

puts by_value(data, "Complaint").inspect 
# => 3 
+0

爲什麼默認'found [0] [1]'一個? – 2014-11-04 16:26:06

+0

啊!感覺困..所以:-) – 2014-11-04 16:27:36

+0

謝謝,它似乎與少量的數據工作 - 所以我假設有其他地方有什麼問題,我可以工作。會出現投入數據沖洗我所期望的,所以不完全確定。 – 2014-11-04 16:31:00