2017-01-30 82 views
1

我一直在解析HTML中的域和頁面標題中的公司名稱。比方說,我的域名是:Python - 從域和頁面標題解析公司名稱

http://thisismycompany.com

和頁面標題是:

This is an example page title | My Company

我的假設是,當我符合這些最長公共子,lowercasing和刪除後所有,但字母數字,這很可能是公司的名稱。

所以最長的公共子串(Link to python 3 code)將返回mycompany。我怎麼去匹配這個子字符串回到原來的頁面標題,以便我可以檢索空白和upercase字符串的正確位置。

回答

1

我認爲這是否可以使用正則表達式,但我認爲只使用正常的字符串操作/比較會更容易,尤其是因爲這看起來不像時間敏感的任務。

def find_name(normalized_name, full_name_container): 
    n = 0 
    full_name = '' 
    for i in range(0, len(full_name_container)): 
    if n == len(normalized_name): 
     return full_name 

    # If the characters at the current position in both 
    # strings match, add the proper case to the final string 
    # and move onto the next character 
    if (normalized_name[n]).upper() == (full_name_container[i]).upper(): 
     full_name += full_name_container[i] 
     n += 1 

    # If the name is interrupted by a separator, add that to the result 
    elif full_name_container[i] in ['-', '_', '.', ' ']: 
     full_name += full_name_container[i] 

    # If a character is encountered that is definitely not part of the name 
    # Re-start the search 
    else: 
     n = 0 
     full_name = '' 

    return full_name 

print(find_name('mycompany', 'Some stuff My Company Some Stuff')) 

這應該打印出「我的公司」。對空格和逗號等可能中斷規範化名稱的可能項目進行硬編碼可能是您必須改進的一些問題。

+1

真棒。謝謝。這個方法實際上是我一開始就想到的實現,但無法實現。與此同時,我發現了一個不同的實現。我會把它作爲答案加入,所以你,其他人可以檢查出來。 – Lexxxxx

1

我已經通過生成標題的所有可能的子字符串的列表來解決它。然後將它與我從最長的公共子字符串函數中獲得的匹配進行匹配。

def get_all_substrings(input_string): 
    length = len(input_string) 
    return set([input_string[i:j+1] for i in range(length) for j in range(i,length)]) 

longest_substring_match = 'mycompany' 
page_title = 'This is an example page title | My Company' 

for substring in get_all_substrings(page_title): 
    if re.sub('[^0-9a-zA-Z]+', '', substring).lower() == longest_substring_match.lower(): 
     match = substring 
     break 

print(match) 

編輯:source used

+1

我覺得這可能是更好的解決方案。它可能適用於比我更多的情況。然而,礦井可能更簡單的例子更有效率。 – FreakJoe

+1

我同意。另一個改進可能是將兩個循環組合起來,並在找到匹配項時讓其中斷。這意味着它需要更少的子串,而不是所有的子串(除非最後一個是匹配的子串) – Lexxxxx