gpt4 book ai didi

python - 如何解决/什么是 Python/Pandas 中的 KeyError?

转载 作者:太空狗 更新时间:2023-10-30 01:21:25 26 4
gpt4 key购买 nike

我有两个希望使用 Pandas 处理的文本文件。这些文件以完全相同的方式创建并且非常相似,除了内部的一些内容。但是,我的程序不能处理其中一个文本文件,但可以处理另一个文件。这是我的错误:

Traceback (most recent call last):
File "E:\Holiday Project\Politic\store.py", line 19, in <module>
tweets['text'] = list(map(lambda tweet: tweet['text'], tweets_data))
File "E:\Holiday Project\Politic\store.py", line 19, in <lambda>
tweets['text'] = list(map(lambda tweet: tweet['text'], tweets_data))
KeyError: 'text'

这是我的代码:

import json
import pandas as pd
from textblob import TextBlob

tweets_data_path = 'filename.txt'

tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue

print (len(tweets_data))

tweets = pd.DataFrame()
tweets['text'] = list(map(lambda tweet: tweet['text'], tweets_data))
tweets['lang'] = list(map(lambda tweet: tweet['lang'], tweets_data))
tweets['country'] = list(map(lambda tweet: tweet['place']['country'] if tweet['place'] != None else None, tweets_data))
avg = 0
for lol in tweets['text']:
tweet = TextBlob(text)
avg = tweet.sentiment.polarity + avg
avg = avg/len(tweets)
print(avg)

最佳答案

tweet['text'] 似乎不存在。当您尝试访问不存在的 HashMap /字典中的键时,会生成键错误。例如

myDict = {"hello": 1, "there": 2}
print myDict["hello"] #this prints 1
print myDict["friend"] #this will generate a key error because it does not exist

关于python - 如何解决/什么是 Python/Pandas 中的 KeyError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31274243/

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