2

我是 python 新手。我有一个简单的程序来查找一个词在网站中被使用的次数。

opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]

url = 'http://en.wikipedia.org/wiki/Albert_Einstein'
ourUrl = opener.open(url).read()
soup = BeautifulSoup(ourUrl)
dem = soup.findAll('p') #find paragraphs
for i in dem:    # loop for each para

    words = re.findall(r'\w+', i.text)   
    cap_words = [word.upper() for word in words]
    word_counts = Counter(cap_words)
    print word_counts

事情是这给了我逐段的字数,而不是网站的总字数。需要什么改变。另外,如果我想过滤掉常见的文章,例如 a,an,我需要包含哪些代码。

4

1 回答 1

1

假设您真的只想找到段落中包含的单词,并且对您的正则表达式感到满意,这是获得检索文档总字数的最小更改:

soup = BeautifulSoup(ourUrl)
dem = soup.findAll('p') #find paragraphs
word_counts = Counter()
for i in dem:    # loop for each para
    words = re.findall(r'\w+', i.text)
    cap_words = [word.upper() for word in words]
    word_counts.update(cap_words)

print word_counts

要忽略常见单词,一种方法是定义一组可忽略的单词:

word_counts = Counter()
stopwords = frozenset(('A', 'AN', 'THE'))
for i in dem:    # loop for each para
    words = re.findall(r'\w+', i.text)
    cap_words = [word.upper() for word in words if not word.upper() in stopwords]
    word_counts.update(cap_words)
于 2013-07-28T02:19:59.970 回答