首页 > 解决方案 > 输出保持垂直打印

问题描述

我能够编写一个 API 调用来从公共 API 检索歌词(特别是 Dance Gavin Dance 的尴尬。问题是,当它打印时,它会逐个字母地打印歌词,而不是垂直地打印它在 API 上显示的方式. 这是代码:

import json
import requests

api_url_base = 'https://api.lyrics.ovh/v1/'
headers = {'Content-Type': 'application/json',
           'charset': 'utf-8'}

def get_lyrics_info():

        api_url ='{0}Dance%20Gavin%20Dance/Awkward'.format(api_url_base)
        response = requests.get(api_url, headers=headers)

 if response.status_code == 200:
       return json.loads(response.content.decode('utf-8'))
   else:
       return None

lyric_info = get_lyrics_info()

if lyric_info is not None:
   print("Here is your info: ")
   for lyrin in lyric_info["lyrics"]:
      print(lyrin)

else:
   print('[!] Request Failed')

这是输出的样子(这只是输出的一部分,只是为了向您展示它的外观):

D
o
n
'
t

m
a
k
e

t
h
i
s

a
w
k
w
a
r
d

我曾尝试使用 wrap() 函数、fill() 函数,但变量“lyrin”不是字符串。我怎样才能解决这个问题?

标签: python-3.xrestapipython-3.4

解决方案


for lyrin in lyric_info["lyrics"]将遍历所有chars Usefor lyrin in lyric_info["lyrics"].split('\n'):

或者做sys.stdout.write(lyrin)

import json
import requests

api_url_base = 'https://api.lyrics.ovh/v1/'
headers = {'Content-Type': 'application/json',
           'charset': 'utf-8'}

def get_lyrics_info():
   api_url ='{0}Dance%20Gavin%20Dance/Awkward'.format(api_url_base)
   response = requests.get(api_url, headers=headers)

   if response.status_code == 200:
       return json.loads(response.content.decode('utf-8'))
   else:
      return None

lyric_info = get_lyrics_info()

if lyric_info is not None:
      print("Here is your info: ")
      for lyrin in lyric_info["lyrics"].split('\n'):
         print(lyrin)

else:
       print('[!] Request Failed')

或者

import json
import requests
import sys

api_url_base = 'https://api.lyrics.ovh/v1/'
headers = {'Content-Type': 'application/json',
           'charset': 'utf-8'}

def get_lyrics_info():
   api_url ='{0}Dance%20Gavin%20Dance/Awkward'.format(api_url_base)
   response = requests.get(api_url, headers=headers)

   if response.status_code == 200:
       return json.loads(response.content.decode('utf-8'))
   else:
      return None

lyric_info = get_lyrics_info()

if lyric_info is not None:
      print("Here is your info: ")
      for lyrin in lyric_info["lyrics"]:
         sys.stdout.write(lyrin)

else:
       print('[!] Request Failed')

推荐阅读