Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python抓取英语单词_Python_Nlp_Urllib2_Web Scraping_Urllib - Fatal编程技术网

使用Python抓取英语单词

使用Python抓取英语单词,python,nlp,urllib2,web-scraping,urllib,Python,Nlp,Urllib2,Web Scraping,Urllib,我想把《纽约时报》头版的所有英文单词都删掉。我用Python写了这样的东西: import re from urllib import FancyURLopener class MyOpener(FancyURLopener): version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' opener = MyOpen

我想把《纽约时报》头版的所有英文单词都删掉。我用Python写了这样的东西:

import re
from urllib import FancyURLopener

class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'            

opener = MyOpener()
url = "http://www.nytimes.com"
h = opener.open(url)
content = h.read()
tokens = re.findall("\s*(\w*)\s*", content, re.UNICODE) 
print tokens
这工作正常,但我得到的HTML关键字,如“img”,“src”以及英语单词。有没有一种简单的方法可以从Web scaping/HTML中仅获取英语单词


我看了这篇文章,它似乎只讨论了刮削的机制,上面提到的工具都没有讨论如何过滤非语言元素。我不感兴趣的链接,格式等,只是简单的话。任何帮助都将不胜感激

你需要一些英语词典参考。一个简单的方法是使用拼写检查器。我想到了

从PyEnchant网站:

>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>>
在您的情况下,可能是以下几点:

d = enchant.Dict("en_US")
english_words = [tok for tok in tokens if d.check(tok)]
如果这还不够,并且您不希望在HTML标记(如属性)中出现“英语单词”,那么您可能只需要解析重要的文本。

我喜欢为此使用:

# copypasta from http://lxml.de/lxmlhtml.html#examples
import urllib
from lxml.html import fromstring
url = 'http://microformats.org/'
content = urllib.urlopen(url).read()
doc = fromstring(content)
els = el.find_class(class_name)
if els:
    return els[0].text_content()
然后,为了确保拼凑出来的单词是唯一的英语单词,你可以在从文本文件加载的词典中查找它们,或者在许多很酷的语料库和语言处理工具中查找它们。

你确定你想要“英语”单词吗?从某种意义上说,它们出现在一些词典中?例如,如果你删掉了《纽约时报》的一篇文章,你会想把“奥巴马”(或者说“佩林”也包括在内,即使它们可能还没有出现在任何词典中

在许多情况下,解析HTML(如Bryan所建议的那样使用BeautifulSoup)并只包含文本节点(可能还有一些针对人类的属性,如“title”和“alt”)。

可能是一个不错的选择

导入html2text

打印html2text.html2text(您的html字符串)

您可以将全部替换为零或一个空格。使用re模块,确保您了解贪婪和非贪婪模式匹配。你需要不贪心


然后,一旦你去掉所有标签,应用你使用的策略。

我刚刚意识到这已经得到了回答,以BeatifulSoup和《纽约时报》为例,即使在这里是的,我想要奥巴马和佩林,基本上我想要所有可见的单词,而不仅仅是“英语”单词。很抱歉给你带来了困惑。我不需要字典查找,我也可以将此代码用于其他语言。