2016-11-30 112 views
0

我正在處理一段程序,該程序需要在文本文件中搜索字符串並打印出它所在的行。我正在正在打印字符串段在「if」語句中不起作用

if ingredient[8:] in line : 

沒有結束時,除非我手動鍵入在被在成分保持的字符串:使用以下行的問題[8:]。例如:

if "tomato" in line : 

這很好。我似乎無法弄清楚爲什麼「番茄」或「小扁豆」可以代替「成分[8:]」。

以下是我的代碼:

# VARIABLES 
shoppingList=[] 

# MOVE CONTENTS OF SHOPPING LIST FILE ONTO LIST 
with open("Recipe Shopping List.txt") as f: 
    content = f.readlines() 

def findRecipe(): 

    # PROMPT USER FOR RECIPE NAME 
    print "Enter a recipe name: " 
    recipeInput = raw_input() 
    recipeIndex = content.index(" - " + recipeInput + "\n") 

    # PUT INGREDIENTS INTO SHOPPING LIST 
    for ingredient in content[recipeIndex+1:]: 
     if ingredient.startswith(" -"): 
      # FIND INGREDIENT'S CATEGORY IN CATEGORY FILE 
      with open("Ingredient Category List.txt") as categoryFile : 
       for line in categoryFile : 
        if ingredient[8:] in line : 
         print line 
     else: 
      break 

findRecipe() 

,這裏是存儲在測試文本文件的文本:

「成分分類LIST.TXT」

tomato - produce 
carrot - produce 
celery - produce 
lentil - grains 

「Recipe Shopping List.txt」

- Lentil soup 
    - 2 lentil 
    - 3 tomato 
    - 4 celery 
    - 4 carrot 
    - Gnocchi 
    - 1 tomato 
    - 3 gnocchi 
    - 2 onion 

非常感謝您的幫助。

+0

@leaf感謝您的回覆。 '成分'應該保存像「-2扁豆」這樣的字符串,所以我試圖引用僅包含食物名稱的子字符串,所以在這種情況下我認爲「成分[8:]」只是「扁豆」 。當我打印'成分[8:]'時,我確實得到了「小扁豆」並且是str型。 – user1861051

+1

我的不好。我剛剛意識到我的錯誤。我會刪除我的評論。 –

回答

4

成分[8:]包括換行符。砍了一個字符短:

if ingredient[8:-1] in line: 

更重要的是,分割線,拉出一個你需要的領域,很好地剝離的空白。

+0

工作正常!謝謝。 – user1861051

1
ingredients[8:] 

這條線返回新的生產線一樣,所以例如,而不是:

'lentil' 

它的返回:

'lentil 
' 

您可以將行更改爲:

ingredients[8:].rstrip() 
+0

謝謝!瞭解rstrip()方法真的很好。 – user1861051