我在Django中使用render_to_response
从Views向Javascript发送一个列表。但在Javascript中,我将输入作为字符串,我无法将其转换为数组。
我需要拼接数组以提取3个不同的属性。
sentiment1 变量是我面临错误的属性。
def allexist(request):
response = {}
responseList = []
sentimentlist = []
dt = {}
fetchedhash = []
senti_vals = []
positive_list = []
negative_list = []
neutral_list = []
positive_vals = []
negative_vals = []
neutral_vals = []
sentiments = {}
d = Registered.objects.filter(id=userid).values('projectid', 'pname')
for x in d:
date1 = Registered.objects.filter(projectid=x["projectid"]).values('startdate', 'enddate')
for dt in date1:
end = dt["startdate"]
startd = dt["startdate"].date()
startt = dt["startdate"].time()
endd = dt["enddate"].date()
endt = dt["enddate"].time()
final = datetime.combine(startd, startt)
final2 = final.replace(minute=00, second=00)
finale = datetime.combine(endd, endt)
finale2 = finale.replace(minute=00, second=00)
word_list=[]
e = Hashtagmodel.objects.filter(projectid=x["projectid"]).values('hashtaglist')
for hashes in e:
d = Tweetsmodel.objects.filter(UserID=userid, isoDate__range=(final2, finale2),
TweetText__icontains=hashes["hashtaglist"]).values('isoDate').annotate(
total=Count('TweetText')).order_by('isoDate')
w = Tweetsmodel.objects.filter(UserID=userid, isoDate__range=(final2, finale2),
TweetText__icontains=hashes["hashtaglist"]).values("TokeniZedString")
s = Tweetsmodel.objects.filter(UserID=userid, isoDate__range=(final2, finale2),
TweetText__icontains=hashes["hashtaglist"]).values('senti')
# otherCount = 0
created_at = []
tweet_count = []
response = {}
for data in d:
created_at.append(data['isoDate'])
tweet_count.append(data["total"])
# rowData = str(data['isoDate']) + "," + str(data['total'])
response["date"] = created_at
response["count"] = tweet_count
responseList.append(response)
for i in w:
word_list.append(i["TokeniZedString"])
concat_string = ','.join(word for word in word_list)
concat_list = concat_string.split(",")
counts = Counter(concat_list)
word = []
pingpong = 0
for x in counts:
pingpong = pingpong + 1
if pingpong <= 1000:
word.append({"text": x, "size": counts[x]})
jsonStr = json.dumps(word)
for j in s:
senti_vals.append(j["senti"])
senti_string = ','.join(str(word) for word in senti_vals)
senti_list = senti_string.split(",")
counting = Counter(senti_list)
positive = 0
negative = 0
neutral = 0
for j in counting:
if j == '4.0':
positive = counting[j]
positive_string = "\"positive\":" + str(counting[j])
if j == '0.0':
negative = counting[j]
negative_string = "\"negative\":" + str(counting[j])
if j == '1.0':
neutral = counting[j]
neutral_string = "\"neutral\":" + str(counting[j])
positive_vals = Tweetsmodel.objects.filter(Q(senti="4.0") & Q(TweetText__icontains=hashes["hashtaglist"])).values(
'TweetText')
negative_vals = Tweetsmodel.objects.filter(Q(senti="0.0") & Q(TweetText__icontains=hashes["hashtaglist"])).values(
'TweetText')
neutral_vals = Tweetsmodel.objects.filter(senti="1.0", TweetText__icontains=hashes["hashtaglist"]).values('TweetText')
positive_string = '-----#$$$%%%%____----'.join(str(word) for word in positive_vals)
negative_string = '-----#$$$%%%%____----'.join(str(word) for word in negative_vals)
neutral_string = '-----#$$$%%%%____----'.join(str(word) for word in neutral_vals)
positive_list = positive_string.split("-----#$$$%%%%____----")
negative_list = negative_string.split("-----#$$$%%%%____----")
neutral_list = neutral_string[8:].split("-----#$$$%%%%____----")
stupid = "\n" + "\n"
positive_list = positive_list[:15]
negative_list = negative_list[:15]
neutral_list = neutral_list[:15]
positive_list = [x + stupid for x in positive_list]
negative_list = [x + stupid for x in negative_list]
neutral_list = [x + stupid for x in neutral_list]
# sentiments = [ {"positive": positive, "negative": negative, "neutral": neutral,"data_positive": positive_list, "data_negative": negative_list,"data_neutral":neutral_list}]
sentiments = [{"positive":positive,"negative":negative,"neutral":neutral}]
sentiments1=[{"data_positive": positive_list, "data_negative": negative_list,"data_neutral":neutral_list}]
sentimentlist.append(sentiments)
for alexa in sentimentlist:
print("this is response of senti",alexa)
return render_to_response("personal_anshul/allexist.html", {"responseList": responseList,"jsonStr": jsonStr ,"sentimentlist": sentimentlist,"jsonStr1":sentiments1,"e":e})
return render(request, "personal_anshul/allexist.html")
HTML文件代码段:将sentiment1的值(文本)传递给my_var4
<script>
var my_var = "{{ responseList }}";
var my_var2 = "{{ jsonStr }}";
var my_var3 = "{{ sentimentlist }}";
var my_var4 = "{{ jsonStr1 }}";
var my_var5 = "{{ e }}";
</script>
Javascript片段:
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
//console.log(my_var4);
L=decodeHtml(my_var4);
console.log(typeof(L))
values = L.split(",/s")
console.log(values)
console.log(typeof(values))
L的输出:
以下是使用console.log(my_var4)的my_var4变量的输出
***
[{'data_neutral': ["ext': 'The 5 best deals on #Amazon right now will all make life easier /w60T7iCynr via @enquirer /ly0W1urLs4'}
", "{'TweetText': 'Reining in Big Data’s Robber\xa0Barons /EL3pu1VS0J #Facebook #Twitter #Amazon /8XiTEG0sPi'}
", "{'TweetText': ' /7WJqcDbzNp Promote #Amazon #Affiliate products AUTOMATICALLY with /2cDsaTmPbm #SeoExpert… /nVXBPXUQMm'}
", "{'TweetText': 'RT @Oldbrookender: Best Selling Action Adventure Series Set in Roman Britain\nFree on Kindle Unlimited\n#iartg #histfic #Rome\n#amazon #bestse…'}
", "{'TweetText': 'RT @omghotels: View from The Shard &amp; River Cruise for Two - Perfect Gift Experience For Two only £89. \n\n /x9lilcNsfF\n\n#Amazon #g…'}
", "{'TweetText': 'RT @Oldbrookender: Best Selling Action Adventure Series Set in Roman Britain\nFree on Kindle Unlimited\n#iartg #histfic #Rome\n#amazon #bestse…'}
", "{'TweetText': '#Apple, #Google, #Facebook, #Amazon, #Microsoft: Which #Tech Giant Will Fall First? /5hgwF71dDP'}
", "{'TweetText': 'RT @SusanneSpellman: #The Virus- Book 1 #Amazon /#ITunes /#B&amp;N\n /9hB7mvKFZQ\n\nThe Virus #Book 2 (Coming Soon)\n /Vbcae…'}
", "{'TweetText': 'RT @Dolors111068: LA MANSIÓN DE LOS NAVAS... de @ja_gonzalez49 Una de las novelas #policíacas más leídas en #Amazon. Ambientada en los año…'}
", "{'TweetText': 'RT @burginvecmo5389: ???????#?????????\n\n??#iTunes???\n10000?×30?\n\n??#Googleplay??? \n10000?×30?\n\n??#Amazon????\n10000?×30?\n\n??????\n\n??????\n?????????…'}
", "{'TweetText': 'RT @mfoulk50: HOLY HUMANITY\nby James Foster\nThought provoking\nperspective after a\nlifetime in ministry\n#amazon\nRT, plz ;}
", "{'TweetText': 'Simplified Steps To Become An Expert #Amazon Seller @Hounddogdigital /qsmAIJTvKW /5wEJ6CuqKJ'}
", '{'TweetText': '"nothing less than perfection" WHEN I\'M WEAK /OGLpCoexbJ #Amazon #Kindle #kindlebooks #Christianfiction'}
', "{'TweetText': 'RT @phonandroid: ?? #FnacDarty et #Google s’allient pour contrer le #HomePod et l’#AmazonEcho #GoogleHome &gt; /zYAjATgVq7 ;}
", "{'TweetText': '?[???????!!]GOOD TIMES A COLLECTION OF AMERICAN STANDARDS #????? #LaserDisc ????#amazon ???!!… /8JMkgjIjCn'}
"], 'data_negative': ["{'TweetText': '???????????????????????????????????????? ???? /qxErKTaO8c #books #amazon'}
", '{'TweetText': "4.3 Stars: Women's Plus Size 711 Skinny Ankle Jeans for $30. Great Deal for Today! #Monday #Amazon #Deal [… /0YV0NYeXrg"}
', "{'TweetText': '#UK 26% off: Samsung Level Active Wireless Headphone Black for £59.44. Great Deal for Today! #Monday #Amazon #Deal… /q3gxh6FSu9'}
", "{'TweetText': 'Philo to Add #Apple TV, Android, and #Amazon Fire TV Support @ Cord Cutters News, LLC .. #?????_??????? /IOgmiDMWBr'}
", "{'TweetText': ' /14rCHPGkat\n #Multicultural #Steamy #Romance #Suspense #Contemporary #Free #Book #Kindle #review #amazon /nyOduXxtYT'}
", "{'TweetText': 'RT @mangahack: ?Android???????????\n?????10?? #Amazon???? 500??????????\n????&amp;RT???????????????? ?5/6(?)23:59??\n\n??????????????????????DL?????…'}
", '{'TweetText': "4.4 Stars: Bcbgmax Azria Women's Dara V-neck Dress for $92. Great Deal for Today! #Monday #Amazon #Deal [… /CddVycgV4k"}
', "{'TweetText': 'Return to Cedar Hill \n /ECoYAEDBJS #Free #Book #Kindle #review #amazon #christianfiction #Siblings,… /xpXnczKZpY'}
", "{'TweetText': 'Return to Cedar Hill \n /XkWAarlRSR #Free #Book #Kindle #review #amazon #christianfiction #Siblings,… /YptXML70RR'}
", "{'TweetText': 'RT @corrigenda_es: #DesdeElTragaluz, de @Marie_N_Vianco\n /DGXDhmpzPE \n#Amazon #thriller #novela\nA veces el lugar más inesper…'}
", "{'TweetText': '4.7 Stars: Pat The Patriot Expandable Bangle Bracelet for $32. Great Deal for Today! #Monday #Amazon #Deal [… /lESdb5zcGQ'}
", "{'TweetText': 'RT @SometimesYouDie: Trump Is Right /g8Z0hLkuUf #USPS #Bezos #Amazon #MAGA @cvpayne'}
", "{'TweetText': '??????? (???????) /RxrIgRqVTB #Amazon'}
", "{'TweetText': '#starvingartist /IcSYAiuXPI #socialmediamarketing #blog #blogging #asmsg #IARTG #IAN1 #Amazon #AmWriting #firebirdslight'}
", "{'TweetText': '????????????? /2UkRy4RLur #Amazon'}
"], 'data_positive': ["{'TweetText': 'RT @AuthorEllie: The Dead Wake Anthology #Amazon /d5Rv67z5rl ?????? Are you brave enough? Ten stories to disable you! #zombies…'}
", '{'TweetText': "RT @W_Angels_Wings: Available on #Amazon ~ With Angel's Wings\n /t3EG8ScQre\n#AwardWinner #memoir #specialneeds #parenting #Kindle…"}
', '{'TweetText': "#USA Deals: Women's Printed Inverted Pleat Dress for $38. Great Deal for Today! #Monday #Amazon #Deal [… /zn1Lco1GwC"}
', "{'TweetText': '#Sondage #ecommerce : Pour vos achats en ligne, quel canal privilégiez vous ?\nLe géant américain #Amazon ? Le franç… /06MCMcBJ23'}
", "{'TweetText': '(Actualitté) Chez #Amazon, on pisse dans une bouteille pour éviter des sanctions : Selon.. /Ul8sMwX1T6 /TZ7WVF1HOP'}
", "{'TweetText': 'RT @kurodorifunny: ????????????2?????? #RT??????\n??10??? #Amazon???? 1000??????\n\n?????2??\n?2000RT?4?\n?3000RT?6?\n?4000RT?8?\n?5000RT?10?\n\n????…'}
", "{'TweetText': 'Quantum Field Theory /aUHJorhZ1c #Amazon'}
", '{'TweetText': "5.0 Stars: Women's Velvet Halter Dress for $129. Great Deal for Today! #Monday #Amazon #Deal [… /K7n05rdqpb"}
', "{'TweetText': 'Better With You $25 Blog Tour Giveaway. Enter to win $25 from author Rachel John #Amazon #Paypal /MEOHSnnwRB'}
", "{'TweetText': 'Dark Energy: Theory and Observations /573ji7vjAy #Amazon'}
", "{'TweetText': 'RT @ATAGOofficial: ?\n#Amazon???? 1,000??????!!\n?\n\n1??????????\n? #????????????????????????????? ?\n\n??????\n@ATAGOofficial ????? &amp; ???????RT\n?…'}
", '{'TweetText': "Before we all start thinking of conferring sainthood on #Amazon because it's in 45's crosshairs, read this. And re… /akqRwVmWj0"}
', '{'TweetText': "#USA Deals: Women's Samantha Wrap-front Handkerchief Dress for $148. Great Deal for Today! #Monday #Amazon #Deal [… /kDZIVmD9xD"}
', '{'TweetText': "5.0 Stars: Women's Madalyn Asymmetrical Faux-wrap Dress for $198. Great Deal for Today! #Monday #Amazon #Deal [… /EnNeHOgVND"}
', '{'TweetText': "4.4 Stars, 609 Reviews: Men's Big-tall 560 Comfort-fit Jean for $33. Great Deal for Today! #Monday #Amazon #Deal [… /njf82q8PUa"}
']}]
如果我拆分它我得到一个对象。但我想要一个阵列。如何在此处转换此数据类型。或者我是否需要遵循任何其他方法?