首页 > 解决方案 > 如何使用 TextBlob 创建带双引号的 JSON 文件

问题描述

我正在使用我在网上找到的一些代码,它使用 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'
  },

标签: pythonjson

解决方案


使用json模块。您可能不得不省略该TextBlob元素,因为它没有 JSON 表示。

import json

...

print(json.dumps(tweets))

推荐阅读