2014-04-04 94 views
1

我正在使用re.search在运行时在.txt文件中查找值我得到您需要在屏幕上打印的值,这是运行代码时出现的值。将值保存到python中的文件

https://docs.google.com/file/d/0B1gujcFhb7SyeG9aalFoaXlLd28/edit?usp=drivesdk', 
Traceback (most recent call last): 
    File "url_finder.py", line 5, in <module> 
    print re.search("(?P<url>https?://[^\s]+)", line).group() 
    AttributeError: 'NoneType' object has no attribute 'group' 

https://docs.google.com/file/d/0B1gujcFhb7SyeG9aalFoaXlLd28/edit?usp=drivesdk是我要寻找的价值,所有我想要做的就是这个值保存到一个单独的文本文件,这样我就可以用它来做别的事情。是否有可能停止出现此错误并保存值。或者我想将它设置为返回值,因为此脚本将在脚本中运行。

+0

访问您的文件所需的权限,修复别的东西。更好的是,只是在这里发布,外部链接的代码和错误是不赞成的 –

回答

2

错误表示您的re.search返回None。您正尝试致电match.group()上的None,导致该错误。

若要解决此尝试:

for line in your_file: 
    match = re.search("(?P<url>https?://[^\s]+)", line) 
    if match is not None: 
     return match.group() 

现在,它会返回行..

或者,如果你想将它存储在一个变量,你可以使用match对象,并打印出来一旦找到它。

for line in your_file: 
    match = re.search("(?P<url>https?://[^\s]+)", line) 
    if match is not None: 
     break 

print match.group() 
+0

谢谢,伟大的工程,有无论如何,我可以保存match.group()作为一个变量,即url = re.search。 –

+0

当然,你可以保存'match.group()'或'match'对象。或者,如果您只需要打印它,请用'print'替换'return' – msvalkon