简体   繁体   English

使用 Python 读取文本文件

[英]Reading text files with Python

I have a text file with something like a million lines that are formatted like this:我有一个类似一百万行的文本文件,格式如下:

{"_id":"0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0","parameterId":"visib_mean_last10min","stationId":"06193","timeCreated":1581590344449633,"timeObserved":1577922600000000,"value":11100}

The file has no headers.该文件没有标题。 I want to be able to observe it as an array.我希望能够将它观察为一个数组。

I've tried this:我试过这个:

df = pd.read_csv("2020-01_2.txt", delimiter = ",", header = None, names = ["_id", "parameterId", "stationId", "timeCreated", "timeObserved", "value"])

and while that does sort the files into columns and rows like I want it to it will plot "_id":"0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0" as the first entry where I would only want "0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0" .虽然这确实像我希望的那样将文件按列和行排序,但它会绘制"_id":"0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0"作为我只想要"0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0" "_id":"0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0"的第一个条目"0e1daf84-4e4d-11ea-9f43-ba9b7f2413e0"

How do I plot only the value that comes after each ":" into the array?如何仅将每个“:”之后的值绘制到数组中?

As put it by @mousetail this looks as some kind of json file.正如@mousetail 所说,这看起来像是某种 json 文件。 You may want to do as follows:您可能希望执行以下操作:

import json
mylist = []
with open("2020-01_2.txt") as f:
          for line_no, line in enumerate(f):
              mylist.append([])
              mydict = json.loads(line)
              for k in mydict:
                  mylist[line_no].append(mydict[k])
              mydict= {}

It will output a list of lists, each one of them corresponding to a file line.它将输出一个列表列表,每个列表对应一个文件行。 Good luck!祝你好运!

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

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