2016-11-24 45 views
0

我有这个问题,我希望你能帮助我..Python的正则表达式查找单词

基本上我有一个应用程序,其中我打开一个文件,读取我的文件的话,并通过控制台打印字。但是,如果找不到该单词,我想打印“找不到单词”。

这里是我的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! 

谢谢!

+5

'如果玩具:玩具印刷[0]其他:打印“没有玩具found'' –

回答

1

Do not在多个位置打开file。这是一个不好的做法。在一个地方打开并使用object

content = open('example.txt', 'r').read() 
if 'car' in content: 
    print("found") 
else: 
    print("not found") 
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] 
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' 

注意的是,虽然这个解决方案可以工作,也有一些改进,可以对你的代码进行整体。 改进包括:

  • 使用Python 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'