[英]eliminate white spaces between words using regex in python
我想消除包含多個單詞的句子中2個單詞之間的空白
我的代碼如下所示:
import re
sentence = "open app store"
pattern = re.compile(r'\b([a-z]) (?=[a-z]\b)', re.I)
sentence = re.sub(pattern, r'\g<1>', sentence)
print(sentence)
輸出:
open app store
我想刪除應用程序和商店之間的空白。 我想要類似“打開的應用程序商店”的輸出。
請注意, app
並不總是帶有store
, app
可以帶有其他單詞,例如app maker
。
讓我們看一下您的模式 :它匹配一個單詞邊界,然后將任何ASCII字母捕獲到第1組中,然后匹配一個空格,然后斷言存在單個ASCII字母,后跟單詞邊界。 因此,它可以匹配ab
在My ab string
,而不是app store
。
現在,看來您的app
值是靜態的,僅當app
后面有另一個字時,您才想匹配1個或多個空白。 您可能會遵循兩種策略。
您可以匹配后跟空白和字母的app
,然后刪除空白(請參見此Python演示 ):
re.sub(r"\b(app)\s+([a-z])", r"\1\2", sentence, flags=re.I)
(另請參閱regex演示 ),或者您可以使用app
的已知單詞,僅刪除它們之間的空格:
re.sub(r"\b(app)\s+(store|maker|market|etc)", r"\1\2", sentence, flags=re.I)
這可能為您工作。
>>> import re
>>> sentence = "this is an open app store and this is another open app store."
>>> pattern = re.compile(r'app[\s]store')
>>> replacement = 'appstore'
>>> result = re.sub(pattern, replacement, sentence)
>>> result
'this is an open appstore and this is another open appstore.'
編輯:您可以使用此功能消除任意兩個單詞之間的空格。
import re
def remove_spaces(text, word_one, word_two):
""" Return text after removing whitespace(s) between two specific words.
>>> remove_spaces("an app store app maker app store", "app", "store")
'an appstore, app maker, appstore'
"""
pattern = re.compile(r'{}[\s]*{}'.format(word_one, word_two)) # zero or more spaces
replacement = word_one + word_two
result = re.sub(pattern, replacement, text)
return result
嘗試這個 :
import re
sentence = "This is test"
pattern = re.compile(r'(.*)\b\s+(?=[a-z])', re.I | re.S)
sentence = re.sub(pattern, r'\1', sentence)
print(sentence)
輸出:這個測試
希望對你有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.