【发布时间】:2019-04-16 01:25:34
【问题描述】:
我正在使用我在网上找到的一些代码,它使用 Python 中的 TextBlob 来分析推文的情绪,它生成的 JSON 文件使用单引号,而我需要它使用双引号。我不知道如何在代码中更改它,所以我想知道是否有比我知识更多的人能够提供帮助。
我已经尝试用双引号替换 Notepad++ 中的单引号,但显然这有点棘手,因为我不想替换 Tweets 中写的实际引号和撇号。
"""
Author: Stephen W. Thomas
Perform sentiment analysis using TextBlob to do the heavy lifting.
"""
from textblob import TextBlob
import csv
import re
import operator
tweets = []
def strip_non_ascii(string):
stripped = (c for c in string if 0 < ord(c) < 127)
return ''.join(stripped)
#LOAD AND CLEAN DATA
with open("bachelormonday_tweets.csv", "rt") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
next(reader)
for row in reader:
tweet= dict()
tweet["orig"]=row[0]
tweet["TextBlob"] = TextBlob(tweet["clean"])
tweets.append(tweet)
# DEVELOP MODELS
for tweet in tweets:
tweet["polarity"] = float(tweet["TextBlob"].sentiment.polarity)
tweet["subjectivity"] = float(tweet["TextBlob"].sentiment.subjectivity)
if tweet["polarity"] >= 0.1:
tweet["sentiment"] = 'positive'
elif tweet["polarity"] <= -0.1:
tweet["sentiment"] = 'negative'
else:
tweet["sentiment"] = 'neutral'
tweets_sorted = sorted(tweets, key=lambda k: k["polarity"])
print(tweets)
我想要的是在元素周围有双引号的文本输出,但我得到的是这样的:
{
'orig': 'Who else is waiting for that fence jump from #TheBachelor?? Show us the goods already! @chrisbharrison @coltonpic.twitter.com/x2sMwgmVxg',
'clean': 'who else is waiting for that fence jump from #thebachelor?? show us the goods already! @chrisbharrison @coltonpic.twitter.com/x2smwgmvxg',
'TextBlob': TextBlob("who else is waiting for that fence jump from #thebachelor?? show us the goods already! @chrisbharrison @coltonpic.twitter.com/x2smwgmvxg"),
'polarity': 0.0,
'subjectivity': 0.0,
'sentiment': 'neutral'
},
【问题讨论】:
-
为什么不使用
json模块? -
请提供minimal reproducible example,重点是最小化。您提供的代码远远超出了演示问题的需要。
-
请注意,
TextBlob("...")不是有效的 JSON。您希望生成的 JSON 用什么来代替它? -
Barmar,这并不重要,因为我感兴趣的只是原始推文和情绪。我不是很擅长 Python,也绝对不擅长处理 JSON,所以我才来这里寻求帮助