python-3.x - 我如何在 python 中搜索给定的句子并从该结果中获取最常用的单词?
问题描述
对于我的家庭作业,我需要编写一个 python 程序,用谷歌搜索给定的句子并打印与该搜索相关的最常见的 5 个单词。
怎么可能呢?
有库或 API 吗?
谢谢!!!
编辑
在那个任务中,我需要解决纽约时报的每日难题。为此,我需要使用提供的线索进行谷歌搜索。我一直在寻找某种 API 或库来做到这一点。
我是用硒做的。Selenium 对谷歌搜索或与某种网页问题相关的功能非常强大。
解决方案
我会做更多的研究并先自己尝试一下,这样你就可以就你的方法和正在处理的代码提出更具体的问题。
目前尚不清楚您希望使用什么文本来识别前 5 个最常用的词(即 Google 搜索结果页面中的文本、作为搜索的一部分返回的网站上的实际文本等)或在您的分析中将考虑多少个结果。
话虽如此,我建议您研究以下内容:
要从网络中提取文本,我建议您查看 BeautifulSoup4 库。您可以通过在终端中键入以下内容来安装它:
pip install beautifulsoup4
至于词频,您可以使用 nltk 分析您使用美丽汤返回的文本并获取频率或进行其他基于文本的分析。您可以通过在终端中键入以下内容来安装 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]))
推荐阅读
- java - 如何从 Xpath 中获取 id 作为文本
- powershell - Azure DevOps 中的输出操作系统
- sql - 在 SQL JOIN 中使用 Select * 会为错误的表返回错误的 id 值
- python - 将文件从 Docker 服务 Bash 复制到其他服务
- python - Django表单:如何设置字段的初始值,它当前包含在数据库中的值
- mysql - 通过特定的自定义字段订购 WP 查询,不起作用
- python - 使用 auto_arima(SARIMAX) 和傅里叶项预测具有多个季节性的时间序列
- html - 如何使 div 的大小与其父 div 大小相同
- java - Tomcat 从 ps -ef 对环境变量保密
- cockroachdb - 关闭 cockroachdb 单节点集群中的时间序列数据