不知道为什么列返回零

2024-09-30 01:37:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我尝试使用python的第一周。你会注意到我的问题,我是初学者,可能这是一个非常愚蠢的问题

我正在尝试使用谷歌趋势和改进代码,以获得一些自动化的结果。我有两个代码,第一个工作正常。在第二个示例中,我决定在.txt文件中创建一个列表。它正在读取列表,但出于某种原因,google趋势只返回第一个关键字的数据(以下列中填充为零)

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


Tags: 代码infromimportfordatetimetimeresult
1条回答
网友
1楼 · 发布于 2024-09-30 01:37:30

根据这个问题,我们看到的第一件事是不需要在文本文件中提供“”中的文本

我的意见:

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

相关问题 更多 >

    热门问题