【问题标题】:NameError: name 're' is not defined [duplicate]NameError:名称're'未定义[重复]
【发布时间】:2011-11-19 21:41:57
【问题描述】:

我对 python 很陌生。很新。我从教程中复制了以下内容

#!/usr/bin/python

from urllib import urlopen
from BeautifulSoup import BeautifulSoup

webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read

patFinderTitle = re.compile('<title>(.*)</title>')

patFinderLink = re.compile('<link rel.*href="(.*)"/>')

findPatTitle = re.findall(patFinderTitle,webpage)

findPatLink = re.findall(patFinderLink,webpage)

listIterator = []
listIterator[:] = range(2,16)

for i in listIterator:
    print findPatTitle[i]
    print findPatLink[i]
    print "\n"

我得到错误:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    patFinderTitle = re.compile('<title>(.*)</title>')
NameError: name 're' is not defined

我做错了什么?

【问题讨论】:

  • 您是从哪个教程中复制的?它充满了错误。
  • 那么您应该将您的代码与此处的随附代码进行比较:newthinktank.com/2010/11/…。经过一番整理,我发现它有效。
  • 我回滚了您对该问题的编辑,因为不接受变色龙问题。你不能只是让那些发布你原来问题的答案的人的努力付诸东流。

标签: python


【解决方案1】:

除了缺少import re,您的程序还有另一个错误。在

webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read

您在行尾的read 之后将() 关闭。所以目前webpage 是对.read 方法的引用,它不是.read() 调用的结果。

【讨论】:

    【解决方案2】:

    您需要在代码中导入regular expression module

    import re
    re.compile('<title>(.*)</title>')
    

    【讨论】:

    • 谢谢。我现在收到另一个错误..请查看我的编辑
    • @user522962 webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read 应该是 webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read()
    猜你喜欢
    • 2018-08-01
    • 2020-06-17
    • 2016-07-06
    • 2015-10-22
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多