[英]python - regex replace list of words in a string with nothing
有人幫我解決這個問題。 地址字段中的一些復雜模式。 一些用戶在街道名稱字段中輸入街道名稱和郊區名稱。 需要清潔它們。 但是由於兩種情況,清理工作變得很棘手-
例子:-
df1
Street_Name
Point Chevalier Road Point Che
Point Chevalier Road Point Ch
Point Chevalier Road Point Cheval
Point Chevalier Road Point Chevalier
Kings Road Point Chevalier
Point Chevalier
此處的邏輯是,如果有多個匹配單詞,則僅刪除第二個匹配單詞。 如果只有一個匹配項,但前面有其他單詞,則該名稱應為“道路或街道名稱+郊區名稱”,因此請從中刪除郊區名稱。 如果字段中只有匹配的單詞,則保持原樣。
輸出應該是
Street_Name
Point Chevalier Road
Point Chevalier Road
Point Chevalier Road
Point Chevalier Road
Kings Road
Point Chevalier
我們可以在停用詞列表中獲得郊區名稱的所有可能性。 像這樣
stopwords = ['point c','point ch','point che','point chev','point cheva','point cheval','point chevali','point chevalie','point chevalier']
編輯:
這是我嘗試過的方法,但無濟於事:(
def remove_if_suburb_name(s):
stopwords = ('point c','point ch','point che','point chev','point cheva','point cheval',
'point chevali','point chevalie')
for word in stopwords:
m = re.sub(r'\b'+ word + r'\b','', s.lower(), count = 2)
return m
test['new_street_name'] = test['Street_Name'].apply(lambda x: remove_if_suburb_name(x) if pd.notnull(x) else x)
您可以嘗試以下正則表達式:
(.*)(point\s+c\w+)(.*)point\s+c\w+(.*)|(.+)\bpoint\s+c\w+(.*)
並替換為:
\1\2\3\4\5\6
樣本來源:( 在此處運行 )
import re
regex = r"(.*)(point\s+c\w+)(.*)point\s+c\w+(.*)|(.+)\bpoint\s+c\w+(.*)"
test_str = ("Street_Name\n"
"Point Chevalier Road Point Cheva\n"
"Point chevalier Road Point Chev\n"
"Point Chevalier Road Point Cheval\n"
"Point Chevalier Road Point Chevali\n"
"Kings Road Point Chevalier\n"
"Point Chevalier")
subst = "\\1\\2\\3\\4\\5\\6"
result = re.sub(regex, subst, test_str, 0, re.IGNORECASE | re.MULTILINE)
if result:
print (result)
更新:
您應該構造一個字典,並應用上述正則表達式,然后從字典中獲取停止點並進行轉換...我認為這對所有人來說都是更加可行和易於理解的。 因此,您需要做的是將變量放在上述正則表達式中的point \\ s + c \\ w +處,並從停用詞詞典中獲取數據
我不會在邏輯行的開頭搜索“ c點”。
import re
string = '''
Street_Name
Point Chevalier Road Point Che
Point Chevalier Road Point Ch
Point Chevalier Road Point Cheval
Point Chevalier Road Point Chevalier
Kings Road Point Chevalier
Point Chevalier
'''
def remove_if_suburb_name(data, suburb_startswith):
return re.sub(r'(?<!^) {}.*'.format(suburb_startswith), '', data, flags=re.MULTILINE)
print(remove_if_suburb_name(data=string, suburb_startswith="Point C"))
# Street_Name
# Point Chevalier Road
# Point Chevalier Road
# Point Chevalier Road
# Point Chevalier Road
# Kings Road
# Point Chevalier
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.