2 回答
TA贡献1799条经验 获得超8个赞
问题在于将字符串添加到列表中。
您可能希望循环更加外部,并且您也可以使用enumarete这将为您提供一个同时包含项目及其编号的循环
for i, keyword in enumerate(keywords): gbl['df_'+str(i)] = ... something using keyword ...
TA贡献1836条经验 获得超13个赞
from pytrends.request import TrendReq
pytrend = TrendReq(hl='de', tz=390, retries=10, backoff_factor=0.5)
keywords = ['foo', 'bar', 'dummy']
for keyword in keywords:
try:
pytrend.build_payload(
kw_list=[keyword],
geo='DE',
timeframe = 'now 1-d')
gbl = globals()
for i in range(len(keywords)):
gbl['df_'+str(i)] = pytrend.interest_over_time()
gbl['df_'+str(i)] = gbl['df_'+str(i)].drop(labels=['isPartial'],axis='columns')
print(keyword + ' was successfully pulled from Google Trends')
except Exception as e:
print(keyword + ' was not successfully pulled because of the following error: ' + str(e))
continue
我对你的代码做了一些更改并且它起作用了。
这是输出。
foo was successfully pulled from Google Trends
bar was successfully pulled from Google Trends
dummy was successfully pulled from Google Trends
上面代码的问题是您无法将列表附加到字符串。
gbl['df_'+[str(i) for i in range(len(keywords))]] = pytrend.interest_over_time()
gbl['df_'+[str(i) for i in range(len(keywords))]] = gbl['df_'+[str(i) for i in range(len(keywords))]]
添加回答
举报