我正在编写一个程序,我需要在文本文件中搜索字符串并打印出它所在的行。我遇到以下行的问题:
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 :(得分:4)
成分[8:] 包含换行符。把它缩短一个字符:
if ingredient[8:-1] in line:
更好的是,拆分线并拉出你需要的一个区域,很好地剥去了空白区域。
答案 1 :(得分:1)
ingredients[8:]
此行也会返回新行,例如,而不是:
'lentil'
它正在回归:
'lentil
'
您可以将该行更改为:
ingredients[8:].rstrip()