如何从文本文件中读取Python中的列表元素?

2024-05-15 02:14:23 发布

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

我的文本文件如下。在

[0, "we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n"]
[1, "I want to write a . I think I will.\n"]
[2, "@va_stress broke my twitter..\n"]
[3, "\" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry\n"]
[4, "aww great  "Picture to burn"\n"]
[5, "@jessdelight I just played ur joint two s ago. Everyone in studio was feeling it!\n"]
[6, "http://img207.imageshack.us/my.php?image=wpcl10670s.jpg her s are so perfect.\n"]
[7, "cannot hear the new  due to geographic location. i am geographically undesirable. and tune-less\n"]
[8, "\" couples in public\n"]
[9, "damn wendy's commerical got that damn  in my head.\n"]
[10, "i swear to cheese & crackers @zyuuup is in Detroit like every 2 months & i NEVER get to see him!  i swear this blows monkeyballs!\n"]
[11, "\" getting ready for school. after i print out this\n"]

我想从列表中读取每一秒的元素意味着所有的文本tweets进入数组。在

我写的

^{pr2}$

但是当我看到输出时,它只需要每行的第二个字符。在


Tags: thetointhatisonmythis
3条回答

与其猜测数据的格式,不如找出。在

  • 如果您是自己生成的,并且不知道如何在所创建的内容中进行解析,请更改您的代码以生成可以使用生成它的相同库轻松解析的代码,例如JsonLines或CSV。在
  • 如果您是从某个API获取的,请阅读该API的文档并按照文档中的方式进行解析。在
  • 如果有人把文件交给你,让你去解析它,问问别人它是什么格式的。在

有时候,你必须以某种格式处理一些粗糙的旧文件,而这些格式从未被记录下来,也没有人记得它是什么。在这种情况下,你必须对它进行反向工程。但接下来您要做的是猜测可能的可能性,并尝试用尽可能多的验证和错误处理来解析它,以验证您的猜测是否正确。在

在本例中,格式看起来很像JSON lines或{a2}。这两种编码方式都略有不同,每行一个JSON文本,对这些文本、它们的编码方式以及它们之间的空白都有特定的限制。在

因此,虽然像这样的快速脏解析器可能会工作:

with open('tweets.txt') as f:
    for line in f:
        tweet = json.loads(line)
        dosomething(tweet)

您可能希望使用^{}这样的库:

^{pr2}$

当然,quick&dirty解析器在JSON行上工作这一事实是这种格式的一部分,但是如果您实际上不知道是否有JSON行,那么最好确定一下。在

由于您的输入看起来像Python表达式,所以我将使用^{}来解析它们。在

下面是一个例子:

import ast

with open('tweets.txt') as fp:
    tweets = [ast.literal_eval(line)[1] for line in fp]

print(tweets)

输出:

^{pr2}$

在Python中读取文本文件时,这些行只是字符串。它们不会自动转换,所以其他一些数据结构。在

在您的例子中,文件中的每一行都包含一个JSON列表。在这种情况下,您可以首先使用json.loads()来解析行。这会将字符串转换为Python list,然后您可以使用第二个元素:

import json
with open('tweets.txt') as fp:
    tweets = [json.loads(line)[1] for line in fp]

相关问题 更多 >

    热门问题