2015-06-17 49 views
1

我解析文本使用Python和我有這樣的最終代碼寫的句子,但它不能很好地工作:Python和OR語句

 opt = child.get('desc') 
     extent = child.get('extent') 
     if opt == 'es': 
      opt = "ESP:" 
     elif opt == "la": 
      opt = "LAT:" 
     elif opt == "en": 
      opt = "ENG:" 
if opt in ["es","la","en","ar","fr"] and extent == "begin": 
    print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')]) 

它只能與OR語句,但是當我添加AND聲明(我真的需要),沒有什麼變化。請人嗎?

+1

是'opt'變量還是''opt「'字符串?這可能是值得做一個檢查,看看什麼'opt'和'extent'是 – vk1011

+1

應該工作。你能告訴你如何「選擇」和「延長」嗎? – RickyA

+0

根據什麼'opt'和'extent'是'和'和'或'可能可能具有相同的輸出 –

回答

3

除非第一行代碼的輸出是"ar""fr"(或其他不在if-elif的條件中),否則您將覆蓋opt變量。考慮重新命名的「新」 opt別的東西,比如如下:

opt = child.get('desc') 

extent = child.get('extent') 

if opt == 'es': 
    opt2 = "ESP:" 
elif opt == "la": 
    opt2 = "LAT:" 
elif opt == "en": 
    opt2 = "ENG:" 

# Check variable values 
print "opt: ", opt 
print "opt2: ", opt2 

if opt in ["es","la","en","ar","fr"] and extent == "begin": 
    print time, opt2+(" " + opt2).join([c.encode('latin-1') for c in child.tail.split(' ')]) 

我不知道你想從代碼實現什麼,但如果上述至少會得到你的if-else條件滿足原始child.get('desc')條件返回列表中存在的字符串。

1

要通過與運算變成狀況的真實,需要從所有條件結果。

OR

要通過OR操作成爲條件爲真,要求從任何一個條件結果。

E.g.

In [1]: True and True 
Out[1]: True 

In [2]: True and False 
Out[2]: False 

In [3]: True or False 
Out[3]: True 

在你的代碼,打印以下語句:

print "Debug 1: opt value", opt 
print "Debug 2: extent value", extent 

爲什麼又使用相同的變量名?

如果opt值爲es然後如果條件if opt == 'es':Trueopt變量被再次分配給谷ESP:。 而在你最後的if語句中,你檢查了opt in ["es","la","en","ar","fr"],所以總是False。在if語句的第一個條件

opt = child.get('desc') 
# ^^ 
    extent = child.get('extent') 
    if opt == 'es': 
     opt = "ESP:" 
    # ^^ 
    elif opt == "la": 
     opt = "LAT:" 
    elif opt == "en": 
2

您的選擇列表的問題。

如果opt恰好是es,例如,然後

if opt == 'es': 
    opt = "ESP:" 

將它修改成ESP:。然後

if opt in ["es","la","en","ar","fr"] and extent == "begin": 

永遠不能True(當你使用and,而不是or)。

如果更改了該行以類似

if opt in ["ESP:","LAT:","ENG:","ar","fr"] and extent == "begin": 

它可能工作(如果你已經顯示的代碼是所有的相關的問題)。

1

opt就是其中之一:"es", "la", "en"
那麼opt值被改變,這:
if opt in ["es","la","en","ar","fr"] and extent == "begin":
不會通過,因爲opt是錯誤的。

我猜extent等於"begin",所以如果u交換andor它會通過,作爲陳述是正確的。嘗試刪除這個大if/elif/elif並嘗試再次運行and。它應該通過。

0

這是一個運算符優先級問題。你期望的代碼作爲工作:

if (opt in ["es","la","en","ar","fr"]) and (extent == "begin"): 
    print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')]) 

但它可以作爲

if opt in (["es","la","en","ar","fr"] and extent == "begin"): 
    print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')]) 

將計算得到比你預期不同的值。

嘗試第一個代碼段中的括號。