2016-10-02 166 views
1

我正在學習Python字符串操作並試圖將分隔文本轉換爲變量。匹配多個字符串

"On Tap: 20 | Bottles: 957 | Cans: 139"

此字符串應分配20的值,以抽頭957到瓶,和139到罐。該字符串不固定,可能會有所不同(例如,3個值或0,Tap,Bottles或Can的位置也可以互換)。但是它不工作按我的預期,並重新分配瓶的每一次價值

import re 

strEx = "On Tap: 20 | Bottles: 957 | Cans: 139" 
barServingText = strEx.split('|') 
print(barServingText) 
for i in barServingText: 
    print (i) 
    if i.find("Bottles"): 
     print("Found Bottles") 
     Bottles = re.sub('[^0-9]*','',i) 
     print(Bottles) 
    elif i.find("Cans"): 
     print("Found Cans") 
     Cans = re.sub('[^0-9]*','',i) 
     print(Cans) 
    elif i.find("Tap"): 
     print("Found Tap") 
     Tap = re.sub('[^0-9]*','',i) 
     print(Tap) 

到目前爲止,我已經開發了這一點。

輸出:

['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139'] 
On Tap: 20 
Found Bottles 
20 
Bottles: 957 
Found Bottles 
957 
Cans: 139 
Found Bottles 
139 

我已經包含了很多print語句調試代碼。我的目的只是爲適當的變量賦值。

+0

正如你正在嘗試學習python並試圖將字符串轉換爲變量,因此你的變量應該從字符串自動創建,而不是通過將匹配值賦值給你所渲染的變量。應該使用exec(就學習python而言) –

+0

你能舉個例子嗎? –

+0

看我的答案,我已經發布在這裏 –

回答

3

find回報-1時,它無法找到字符串,-1被視爲Truebool(-1)True),所以你必須使用find(...) != -1

import re 

strEx = "On Tap: 20 | Bottles: 957 | Cans: 139" 
barServingText = strEx.split('|') 
print(barServingText) 
for i in barServingText: 
    print (i) 
    if i.find("Bottles") != -1: 
     print("Found Bottles") 
     Bottles = re.sub('[^0-9]*','',i) 
     print(Bottles) 
    elif i.find("Cans") != -1: 
     print("Found Cans") 
     Cans = re.sub('[^0-9]*','',i) 
     print(Cans) 
    elif i.find("Tap") != -1: 
     print("Found Tap") 
     Tap = re.sub('[^0-9]*','',i) 
     print(Tap) 

BTW:與您的數據你不需要re。您可以使用split(和strip

Bottles = i.split(':')[1].strip() 

Cans = i.split(':')[1].strip() 

Tap = i.split(':')[1].strip() 
1

str.find()方法用於在一個字符串返回文本的位置。如果找不到文本,則返回整數-1。在Python中,以檢查是否在字符串中包含另一個,你可能需要使用的語法if subString in string:,就像這樣:

... 
    if "Bottles" in i: 
     print("Found Bottles") 
... 

隨着官方文檔狀態:

對於字符串和字節類型,x in y 只有當且僅當xy的子串時纔是如此。等效試驗y.find(x) != -1

因此,根據您的首選編碼風格和/或特殊需要,可以在「x in y」之間進行選擇或「y.find(x) != -1

1

以下的正則表達式應該爲您創建鍵值對:

r"((.*?):(.*?)(\||$))" 

下面的辦法,但是我覺得更適合,因爲這將使其動態的,可以有比這3個變量更多

import re 

regex = ur"((.*?):(.*?)(\||$))" 

test_str = u"On Tap: 20 | Bottles: 957 | Cans: 139" 

matches = re.finditer(regex, test_str) 

for matchNum, match in enumerate(matches): 
    s=match.group(2).strip().split(' ')[-1]+"="+match.group(3).strip() 
    print(s) 
    exec(s) 

print(Tap) 
print(Bottles) 
print(Cans) 
+0

我覺得這有點完全重寫OP的代碼,而他只是想弄明白爲什麼他的代碼不能按預期工作。 –

+0

@Ben Morris聲明說:「這個字符串不是固定的,可能會有所不同(例如,3個值或0值也可以互換龍頭,瓶子或罐頭的位置)。」那麼用硬編碼方法迭代事情會是一個好的例子嗎?可以使用exec(「%s =%d」%(x,2))將組3的值分配給組2,並動態地進行一些剝離和投射。我的意圖是提出更好的方法...因此,我覺得嘗試的方法是不正確的 –