2011-05-28 133 views
2

我想通過一個字符串數組來循環標題字符串,並查看數組中的哪一個匹配。如何通過字符串數組來查找匹配字符串?

我的代碼工作正常,但我不知道它是否是最有效的方式來做到這一點。

重要的是數組中的字符串不必完全匹配標題中的短語。只要標題中包含每個詞,它們可以以任意順序排列。任何幫助都會很棒。

EX.title = "Apple Iphone 4 Verizon" 
    array = ["iphone apple, verizon iphone", "iphone 3g", "iphone 4", "cool iphone"] 

我需要它返回["iphone apple", "verizon iphone", "iphone 4"]。在字符串「Verizon的iPhone」和「iphone蘋果」的話是在標題中,順序並不重要

results = [] 

#Loop through all the pids to see if they are found in the title 
all_pids = ["iphone 3gs", "iphone white 4", "iphone verizon", "black iphone", "at&t  iphone"] 
title = "Apple Iphone 4 White Verizon" 
all_pids.each do |pid| 
    match = [] 
    split_id = pid.downcase.split(' ') 
    split_id.each do |name| 

     in_title = title.downcase.include?(name) 
     if in_title == true 
     match << name 
     end 
    end 

    final = match.join(" ") 

    if final.strip == pid.strip 
     results << pid 
    end 

end 

print results 

當我運行這一點,打印什麼,我需要["iphone white 4", "iphone verizon"]

回答

2

你可以做類似如下:

>> require 'set' 
=> true 
>> title = "Apple Iphone 4 Verizon" 
=> "Apple Iphone 4 Verizon" 
>> all_pids = ["iphone apple", "verizon iphone", "iphone 3g", "iphone 4", "cool iphone"] 
=> ["iphone apple", "verizon iphone", "iphone 3g", "iphone 4", "cool iphone"] 
>> title_set = Set.new(title.downcase.split) 
=> #<Set: {"apple", "iphone", "4", "verizon"}> 
>> all_pids.select { |pid| Set.new(pid.downcase.split).subset? title_set } 
=> ["iphone apple", "verizon iphone", "iphone 4"] 

你可以做陣列的差異非常類似,但由於它們作爲哈希實現集可能會更快。

+0

我認爲,使用Set的這種替代方法更好,更清潔,沒有使用不必要的輔助變量。 – asaaki 2011-05-31 23:56:38

+0

謝謝..這工作完美。 – blakecash 2011-06-03 05:59:26

+0

很高興聽到! :-)如果這是你正在尋找的答案,你應該接受它(選票旁邊的勾號),以便其他人知道這個問題已經得到了答覆。 – 2011-06-03 08:01:03

2

它看起來對我說,你想找到由嚴格與標題中的字符串相交的字符串組成的字符串。

Array#-執行設定差異操作。 [2] - [1,2,3] = [][1,2,3] - [2] = [1,3]

title = "Apple Iphone 4 White Verizon" 
all_pids = ["iphone 3gs", "iphone white 4", "iphone verizon", "black iphone", "at&t  iphone"] 
set_of_strings_in_title = title.downcase.split 
all_pids.find_all do |pid| 
    set_of_strings_not_in_title = pid.downcase.split - set_of_strings_in_title 
    set_of_strings_not_in_title.empty? 
end 

編輯:改變#find到#find_all返回所有比賽,而不僅僅是第一。

+1

你的答案和我的答案几乎一樣,你比我快。我屈服於你的答案。 – sawa 2011-05-28 04:33:21

+0

有一件事讓我擔憂,它會隨着'all_pids'數組的增長而變慢。首先爲'all_pids'中的術語設置一些查找表可能會降低該效果。 – 2011-05-28 17:04:34

+0

由於某種原因,這只是返回「iPhone白色4」,它也應該返回「iphone verizon」 – blakecash 2011-06-03 06:00:03

相關問題