2014-11-04 53 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