我需要從在 Google 上搜索的 queires 中顯示不同的關鍵字及其頻率(計數)。然后我需要按頻率選擇前 10 個單詞。
輸入示例:
| 地點 | 詢問 |
|---|---|
| google.com | https://www.google.com/search?q=shoe store in new york |
| google.com | https://www.google.com/search?q=new york attractions |
如果選擇 df 來顯示結果,則輸出示例:
| 關鍵詞 | 數數 |
|---|---|
| 鞋 | 1 |
| 店鋪 | 1 |
| 在 | 1 |
| 新的 | 2 |
| 約克 | 2 |
| 景點 | 1 |
所以我從查詢中提取了關鍵字,但我真的不知道下一步該做什么。我會很感激任何幫助
uj5u.com熱心網友回復:
這是一個函式,可用于計算包含查詢的 url 中的關鍵字:
from collections import Counter
from urllib.parse import urlparse
from urllib.parse import parse_qs
def get_keywords_count(url):
return Counter(parse_qs(urlparse(url).query)['q'][0].split())
使用示例:
>>> get_keywords_count('https://www.google.com/search?q=shoe store in new york')
Counter({'shoe': 1, 'store': 1, 'in': 1, 'new': 1, 'york': 1})
您現在可以將它與您的資料框一起使用來獲取總數:
result = pd.DataFrame(
df['query'].apply(get_keywords_count).sum().items(),
columns=['keyword', 'count'],
)
>>> result
keyword count
0 shoe 1
1 store 1
2 in 1
3 new 2
4 york 2
5 attractions 1
uj5u.com熱心網友回復:
我會使用sort_values熊貓方法。
對于您的示例:
import pandas as pd
keyword_count_df = pd.DataFrame({
'keyword':['shoe', 'store', 'in', 'new', 'york', 'attractions'],
'count':[1,1,1,2,2,1]
})
keyword_count_df.sort_values('count', ascending=False).head(10)
uj5u.com熱心網友回復:
可能有更好的方法來做到這一點,但這是我的;
results = ['the','the','plane','bus','plane','light','the']
def countwords(results):
worddict = {}
for result in results:
if result in worddict:
worddict[result] = 1
else:
worddict[result] = 1
return worddict
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439273.html
上一篇:將python串列拆分為子串列
