首页 > 解决方案 > 不知道为什么列返回零

问题描述

这是我尝试使用 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']

标签: pythonpandaslistloopsiterator

解决方案


根据问题,我们看到的第一件事是您不需要在文本文件中提供 '' 中的文本。

我的输入:

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']

推荐阅读