在Python中洗掉以數字開頭并包含句點的字串中的單詞的最佳方法是什么?
this_string = 'lorum3 ipsum 15.2.3.9.7 bar foo 1. v more text 46 2. here and even more text here v7.8.989'
如果我使用正則運算式:
re.sub('[0-9]*\.\w*', '', this_string)
結果將是:
'lorum3 ipsum bar foo v more text 46 here and even more text here v'
我希望這個詞v7.8.989不會被洗掉,因為它是以字母開頭的。
如果洗掉的單詞沒有添加不需要的空間,那就太好了。我上面的正則運算式代碼仍然增加了空間。
uj5u.com熱心網友回復:
您可以使用此正則運算式來匹配要洗掉的字串:
(?:^|\s)(?=[0-9] \.[0-9.]*(?:\s|$))[0-9.]
它匹配:
(?:^|\s): 字串或空格的開頭(?=[0-9] \.[0-9.]*(\s|$)):斷言下一個字符是數字的前瞻;.此字符與字串結尾或下一個空格之間只有數字和s;并且這部分至少有一個.[0-9.]: 一些數字和句點
然后,您可以用空字串替換任何匹配項。在蟒蛇
this_string = 'lorum3 ipsum 15.2.3.9.7 bar foo 1. v more text 46 2. here and even more text here v7.8.989 and also 1.2.3c as well'
result = re.sub(r'(?:^|\s)(?=[0-9] \.[0-9.]*(?:\s|$))[0-9.] ', '', this_string)
輸出:
lorum3 ipsum bar foo v more text 46 here and even more text here v7.8.989 and also 1.2.3c as well
uj5u.com熱心網友回復:
如果您不想使用正則運算式,也可以使用簡單的字串操作:
res = ''.join(['' if (e.startswith(('0','1','2','3','4','5','6','7','8','9')) and '.' in e) else e ' ' for e in this_string.split()])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512315.html
