python - 如何使用 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'
},
解决方案
使用json
模块。您可能不得不省略该TextBlob
元素,因为它没有 JSON 表示。
import json
...
print(json.dumps(tweets))
推荐阅读
- sql - 是否有模仿 nvl() 的 Python fn 或者我可以使用 SQL 来做到这一点?
- biztalk - BizTalk-2016 Feature Pack 3 在累积更新 6 之后安装
- php - Laravel - 检查集合是否有关系
- python - virtualenv 安装包(先激活虚拟环境)与 pipenv 安装包(稍后激活虚拟环境)?
- azure - 在 azure vm 上运行 ansible 的库错误
- java - 如何在需要权限时暂停应用程序
- javascript - 如何通过获取获取查询字符串参数以在另一个文件中的另一个函数中使用?
- microdata - Shopware 丰富的代码片段增加了产品问题
- python-3.x - 在这种情况下,“:”冒号对索引有什么作用?
- primefaces - 通过 PrimeFaces 选择器 (PFS) 更新 RequestContext