gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:33:06 26 4
gpt4 key购买 nike

我的文本文件如下所示。

[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 = []
for line in open('tweets.txt').readlines():
print line[1]
tweets.append(line)

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

最佳答案

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

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

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

关于python - 如何从文本文件中读取Python中的列表元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49780991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com