我有这个问题,希望你能帮帮我..
基本上我有一个应用程序,我打开一个文件,从我的文件中读取单词并通过控制台打印该单词。但我想在没有找到这个词的情况下打印“没有找到的词”。
这是我的python:
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
这是我的文本文件:
车红
玩具绿色
我通过控制台得到了这个:
red
green
如你所见,工作得很好,但如果我的文件中没有“玩具”这个词。有一种方法可以通过控制台获得这样的东西:
Red
No toy found!
谢谢!
答案 0 :(得分:1)
Do not
在多个位置打开file
。这是一个不好的做法。在一个地方打开并使用object
。
content = open('example.txt', 'r').read()
if 'car' in content:
print("found")
else:
print("not found")
答案 1 :(得分:1)
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
if car == []:
print "No car found"
else:
print car[0]
if toy == []:
print "No toy found"
else:
print toy[0]
答案 2 :(得分:1)
不要立即打印toy[0]
,而是在打印到控制台之前使用if-else
语句检查是否有玩具。如果没有玩具,请打印"没有找到玩具"。
根据您提供的代码示例,解决方案如下所示:
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
if toy:
print toy[0]
else:
print 'No toy found'
if car:
print car[0]
else:
print 'No car found'
请注意,虽然此解决方案可能有效,但总体上可以对您的代码进行一些改进。 改进包括:
with
语句轻松关闭您打开的文件find
的变量,因为它是Python中的关键字,可能会在您的应用程序中导致意外行为content
变量中保存的数据进行正则表达式匹配(这样您就不必再次从文件中读取数据)。这些改进将为您提供如下代码: 导入重新
#use with statement to open and close file cleanly
with open('example.txt','r') as f:
# save file contents in the content variable so you don't need to open the file again
content = f.read()
# use data stored in content variable for your regular expression match
car = re.findall('car\s(.*?)\s',content)
toy = re.findall('toy\s(.*?)\s',content)
if toy:
print toy[0]
else:
print 'No toy found'
if car:
print car[0]
else:
print 'No car found'