简体   繁体   English

从获取请求到 python pandas 数据帧的文本响应,不包括开始和结束行

[英]text response from get request into a python pandas data frame excluding begin and end lines

I am new to python, I am working on code that performs a get request from an api and returns the response in a text format and when I use我是 python 的新手,我正在编写从 api 执行获取请求并以文本格式返回响应的代码,当我使用

print(response.text)

I get the response in the below format -我收到以下格式的回复 -

ResponseBegin
Name|Age|Gender|Country
"ABC"|23|M|USA
"ABCD"|21|F|CAN
ResponseEnd

Can anyone please advise how to convert this into a pandas dataframe and also remove the ResponseBegin and ResponseEnd lines at the beginning and ending making the second row as the column header using |谁能建议如何将其转换为 pandas dataframe 并删除开头和结尾的 ResponseBegin 和 ResponseEnd 行,使第二行成为 Z099FB995346F31C749F6E40EDB0F9 列as a delimiter.作为分隔符。

Thank you very much for your advise.非常感谢您的建议。

Thank you谢谢

It's more helpful if you do not show what print(response.text) contains, but just what response.text contains, since the print function is doing some formatting for human readability.如果您不显示print(response.text)包含的内容,而只显示response.text包含的内容,则会更有帮助,因为 print function 正在为人类可读性进行一些格式化。

But I will assume that response.text is just a single string that looks like this:但我会假设response.text只是一个看起来像这样的字符串:

'ResponseBegin\nName|Age|Gender|Country\n"ABC"|23|M|USA\n"ABCD"|21|F|CAN\nResponseEnd'

Notice the \n , which is the "newline" character.注意\n ,它是“换行符”字符。

There are several ways to solve this, but the easiest (fewest lines of code) I think is to export it to a CSV file and then read it in:有几种方法可以解决这个问题,但我认为最简单的(代码行最少)是将其导出到 CSV 文件,然后将其读入:

with open('mydf.csv', 'w') as fh:
   fh.write(response.text)

import pandas as pd
df = pd.read_csv('mydf.csv', sep='|', skiprows=1, skipfooter=1)

You can read more about read_csv for all of its handy tools, but here I am using:您可以阅读有关read_csv的所有便捷工具的更多信息,但我在这里使用:

  • sep : the thing to use as a separator, | sep : 用作分隔符的东西, | in your case在你的情况下
  • skiprows / skipfooter : the number of lines at the beginning or end to skip skiprows / skipfooter :要跳过的开头或结尾的行数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM