我是 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,我需要包含哪些代码。
请您参考如下方法:
假设您真的只想查找段落中包含的单词,并且对您的正则表达式感到满意,这是获得检索到的文档的总字数的最小更改:
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)
