我正在处理一段程序,该程序需要在文本文件中搜索字符串并打印出它所在的行。我正在正在打印字符串段在“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
非常感谢您的帮助。
@leaf感谢您的回复。 '成分'应该保存像“-2扁豆”这样的字符串,所以我试图引用仅包含食物名称的子字符串,所以在这种情况下我认为“成分[8:]”只是“扁豆” 。当我打印'成分[8:]'时,我确实得到了“小扁豆”并且是str型。 – user1861051
我的不好。我刚刚意识到我的错误。我会删除我的评论。 –