2014-11-13 55 views
0

我工作的一個小項目,需要一些幫助,在字符串中搜索文本文本分類,並在Python

可以說我有一個主要的字符串1,例如搜索:貸款協調員

可以說我有另一個字符串2,如:金融助學貸款協調

可以說我有另一個STRING3如:貸款操作

可以說我有另一串,4,如:協調

可以說我有另外一個string5例如:財務助理

。 。

在Python中,找到與string1有關的所有字符串的最佳方法是什麼? 例如:

字符串2必須處理,因爲該字符串中的文本貸款協調員與串1

串3有一些事情,因爲這個詞貸款做

字串4有事情做因爲這個詞協調員

字符串5無關,所以我不在乎這個字符串。

2,3和4應返回FOUND或指示存在小匹配的內容。

..

感謝您的協助!

+2

你已經嘗試了什麼,也給預期的輸入和預期的輸出 – Hackaholic

+0

是否「錢」與「貸款協調員」呢? 「經理」怎麼樣?另一方面,「rdina」呢?我認爲你的要求有點低估。 – neminem

+0

@ hackaholic我還沒有嘗試過任何東西,因爲我不知道從哪裏開始搜索字符串。我沒有要求python代碼,只是建議從哪裏開始。 –

回答

1

您可以使用設定的交集。在您的字符串中製作一組獨特的字詞進行比較。然後從其他每個字符串中的單詞集合中取出交集。保留任何具有非空交點的字符串。

>>> s1 = 'Loan Coordinator' 
>>> sList = ['Financial Student Loan Coordinator', 'Loan Operator', 'Coordinator', 'Financial Assistant'] 

>>> unique = set(s1.split()) # unique words in string 1 

>>> [i for i in sList if unique & set(i.split())] 
['Financial Student Loan Coordinator', 'Loan Operator', 'Coordinator'] 
1
#!/usr/bin/env python 
import sys 


def tokenise(s): 
    return set([word.lower() for word in s.split()]) 


def match_strings(primary, secondary): 
    primary_tokens = tokenise(primary) 
    secondary_tokens = tokenise(secondary) 

    matches = primary_tokens.intersection(secondary_tokens) 
    if matches: 
     print "{} matches because of {}".format(secondary, ", ".join(matches)) 
    else: 
     print "{} doesnt match".format(secondary) 


if __name__ == "__main__": 
    primary = sys.argv[1] 
    secondaries = sys.argv[2:] 

    for secondary in secondaries: 
     match_strings(primary, secondary) 

運行代碼:

~/string_matcher.py "Loan Coordinator" "Financial Student Loan Coordinator" "Loan Operator" "Coordinator" "Financial Assistant" 
Financial Student Loan Coordinator matches because of coordinator, loan 
Loan Operator matches because of loan 
Coordinator matches because of coordinator 
Financial Assistant doesnt match