将google建议结果转换为txt-fi

2024-04-25 02:21:52 发布

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

我使用以下代码来搜集google的建议:

with open(inputfile, 'r', encoding="ISO-8859-1") as inputf:
    for line in inputf:
        line = line.strip("\n")
        URL="http://suggestqueries.google.com/complete/search?client=firefox&q=" + line
        headers = {'User-agent':'Mozilla/5.0'}
        response = requests.get(URL, headers=headers)
        result = json.loads(response.content.decode('utf-8'))
        print(result)
        with open(outputfile, 'a') as file:
            for num in range(len(result)):
                file.write(result[num] + '\n')
                print('wrote: %s ' %(result[num]))

输入文件:

online games
ofline games
free online games
mods
game
gaming

json输出:

['game', ['game mania', 'game of thrones', 'games', 'game of thrones season 8',
          'game of thrones season 7', 'game night', 'gamemeneer', 'gamegear',
          'game pc', 'gamescom']]

我想要的是将每个结果输出到文本文件中的新行。 示例:

game mania\n
game of thrones\n
games\n
ect

但我得到了以下错误:

    File "modules/keyword-suggestion-scraper.py", line 50, in <module>
    file.write(result[num] + '\n')
TypeError: can only concatenate list (not "str") to list

Tags: ofingameaswithgooglelineresult
1条回答
网友
1楼 · 发布于 2024-04-25 02:21:52

get your output to a list, then itterate through that list as you add your value to the text file like this:

mylist = ['one','two','three']
with open('newtext.txt', 'a') as file:
    for num in range(len(mylist)):
        file.write(mylist[num] + '\n')
        print('wrote: %s ' %(mylist[num]))

newtext.txt

one
two
three

相关问题 更多 >