社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

我如何在python中搜索给定的句子并从结果中获取最常用的单词?[关闭]

GhostDede • 7 年前 • 2128 次点击  

对于我的家庭作业,我需要编写一个python程序,用google搜索给定的句子并打印与该搜索相关的最常用的5个单词。

怎么能这么做?

有库或api吗?

谢谢!!!!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40463
文章 [ 1 ]  |  最新文章 7 年前
Justin
Reply   •   1 楼
Justin    7 年前

我会做更多的研究,并尝试自己先这样做,以便您可以问更多的具体问题,您的方法和代码,您正在工作。

目前还不清楚您希望使用什么文本来识别前5个最常见的单词(即google搜索结果页面中的文本、作为搜索一部分返回的网站上的实际文本等),也不清楚您的分析中会考虑多少结果。

话虽如此,我还是建议调查一下:

对于从web中提取文本,我建议您查看图书馆beautifulsoup4。您可以通过在终端中键入以下内容来安装它:

pip install beautifulsoup4

至于词频,你可以使用nltk来分析你用beautifuldsoup返回的文本,得到词频,或者进行其他基于文本的分析。您可以通过在终端中键入以下内容来安装NLTK:

pip install nltk

如果您反对使用nltk进行文本分析,那么可以使用内置库执行类似的操作,以获取某些文本中最常见的单词的计数:

# import your libraries
import re
from collections import Counter

# clean text from google retrieved with beautiful soup
text_from_google = 'This is some example text I use where I use the word 
example more than once for example'
text = text_from_google.lower().split()

# create a function to return the top n words in text
def get_top_words(text, num_words):

    # basic pre-processing to remove punctuation
    punc_filter = re.compile('.*[A-Za-z0-9].*')
    filtered_text = [word for word in text if punc_filter.match(word)]

    word_counts = Counter(filtered_text)

    return word_counts.most_common(num_words)

# get the top words
top_words = get_top_words(text, 5)

for word in top_words:
    print('The word {} was found {} times'.format(word[0], word[1]))