我認爲這是否可以使用正則表達式,但我認爲只使用正常的字符串操作/比較會更容易,尤其是因爲這看起來不像時間敏感的任務。
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'))
這應該打印出「我的公司」。對空格和逗號等可能中斷規範化名稱的可能項目進行硬編碼可能是您必須改進的一些問題。
真棒。謝謝。這個方法實際上是我一開始就想到的實現,但無法實現。與此同時,我發現了一個不同的實現。我會把它作爲答案加入,所以你,其他人可以檢查出來。 – Lexxxxx