python - 不知道为什么列返回零
问题描述
这是我尝试使用 python 的第一周。您会通过我的问题注意到我是初学者,这可能是一个非常愚蠢的问题。
我正在尝试使用谷歌趋势并改进代码以获得一些自动化结果。我有两个代码,第一个工作完美。在第二个中,我决定在 .txt 文件中创建一个列表。它正在读取列表,但由于某种原因,谷歌趋势仅返回第一个关键字的数据(它在以下各列中填充为零)。
代码 1 - 工作正常
import pytrends
from pytrends.request import TrendReq
import pandas as pd
import time
import datetime
from datetime import datetime, date, time
pytrend = TrendReq()
searches = ['detox', 'water fasting', 'benefits of fasting', 'fasting benefits',
'acidic', 'water diet', 'ozone therapy', 'colon hydrotherapy', 'water fast']
groupkeywords = list(zip(*[iter(searches)]*1))
groupkeywords = [list(x) for x in groupkeywords]
dicti = {}
i = 1
for trending in groupkeywords:
pytrend.build_payload(trending, timeframe = 'today 3-m', geo = 'GB')
dicti[i] = pytrend.interest_over_time()
i+=1
result = pd.concat(dicti, axis=1)
result.columns = result.columns.droplevel(0)
result = result.drop('isPartial', axis = 1)
result.reset_index(level=0, inplace=True)
print(result)
代码 2 - 不起作用。我在与代码相同的文件夹中创建了一个 txt 文件“test”。
这是2个代码:
import pytrends
from pytrends.request import TrendReq
import pandas as pd
import time
import datetime
import sys
from datetime import datetime, date, time
pytrend = TrendReq()
file = open('test.txt','r')
f = file.readlines()
file.close()
searches = []
for line in f:
searches.append(line.strip())
groupkeywords = list(zip(*[iter(searches)]*len(searches)))
groupkeywords = [list(x) for x in groupkeywords]
dicti = {}
i = 1
for trending in groupkeywords:
pytrend.build_payload(trending, timeframe = 'today 3-m', geo = 'GB')
dicti[i] = pytrend.interest_over_time()
i+=1
result = pd.concat(dicti, axis=1)
result.columns = result.columns.droplevel(0)
result = result.drop('isPartial', axis = 1)
result.reset_index(level=0, inplace=True)
print(result)
在尝试了很多不同的事情之后,我意识到当我更改单词时(在搜索中),即使是第一个代码也不起作用。下面的示例不起作用:
searches = ['Casillero del Diablo', 'Don Melchor', 'Marques de Casa Concha', 'CdD Reserva Especial', 'Cono Sur Organico']
解决方案
根据问题,我们看到的第一件事是您不需要在文本文件中提供 '' 中的文本。
我的输入:
detox,
water fasting,
benefits of fasting,
fasting benefits,
acidic,
water diet,
ozone therapy,
colon hydrotherapy,
water fast
其次,您需要在分隔符上拆分行并将其附加到搜索中。
searches = []
for line in f:
searches.append(line.split(',')[0])
这是确保根据需要搜索数组:
输出 :
Out[13]:
['detox',
'water fasting',
'benefits of fasting',
'fasting benefits',
'acidic',
'water diet',
'ozone therapy',
'colon hydrotherapy',
'water fast']
推荐阅读
- asp.net-core - 无需向 URL 传递很长的字符串即可获得 HTTP 请求?
- python - 如何从 DailyMotion Video Api 获得十多个结果?
- indexing - 将 bash 代码转换为蛇文件时出错
- ejs - 我们如何在 ejs 模板中需要一个参数,以便在参数未定义时 ejs.render 失败?
- react-native - 未处理的 JS 异常:不变违规:使用 React-Redux Connect #15822 的钩子调用无效
- generics - 使用嵌套泛型初始化 kotlin 映射
- powershell - Powershell Start-Process -NoNewWindow 不与 -Credentials 一起使用
- typescript - 返回类型
其中 F 是返回类型 Promise 的函数 - python - Visual Studio Code 中的 Python 扩展会换行并移动代码
- wso2 - WSO2 APIM 不会在集群设置中更新已发布的 API