![](/img/trans.png)
[英]Fix the words and remove the unwanted spaces between splitted word using python?
[英]Remove unwanted spaces between quotations
有沒有更優雅的方法來刪除引號之間的空格(盡管使用如下代碼:
input = input.replace('" 12 "', '"12"')`)
從這樣的一句話:
At " 12 " hours " 35 " minutes my friend called me.
事情是數字可以改變,然后代碼將無法正常工作。 :)
只要您的引文合理,您就可以使用正則表達式:
re.sub(r'"\s*([^"]*?)\s*"', r'"\1"', input)
該模式讀作“引號,任意數量的空格,不是引號的東西(捕獲),后跟任意數量的空格和引號。替換就是您在引號中捕獲的內容。
請注意,捕獲組中的量詞是不情願的。 這可確保您不會捕獲尾隨空格。
您可以嘗試使用正則表達式,如下所示:
"\s+(.*?)\s+"
這匹配任何長度的任何 substring 包含任何不是換行符的字符,由空格和引號包圍。 通過將此傳遞給re.compile()
,您可以使用返回的Pattern
object 來調用sub()
方法。
>>> import re
>>> string = 'At " 12 " hours " 35 " minutes my friend called me.'
>>> regex = re.compile(r'"\s+(.*?)\s+"')
>>> regex.sub(r'"\1"', string)
'At "12" hours "35" minutes my friend called me.'
\1
要求替換第一組,在本例中為匹配的字符串.*?
這是我想出的快速解決方案,適用於您輸入的任何數字。
input = 'At " 12 " hours " 35 " minutes my friend called me.'
input = input.split()
for count, word in enumerate(input):
if input[count] == '"':
del input[count]
if input[count].isdigit():
input[count] = '"' + input[count] + '"'
str1 = ' '.join(input)
print('Output:')
print(str1)
Output:
>>> Output:
>>> At "12" hours "35" minutes my friend called me.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.