- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我尝试运行以下代码时,出现 JSONDecodeError 错误。我不知道如何解决它。
我正在尝试流式传输推文。对于几条推文来说它工作正常,突然我收到错误并且流停止,请帮助我如何解决这个问题?更新的完整代码
from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
from googletrans import Translator
import json
import re
import csv
ACCESS_TOKEN = "2446723783-cqGTmWPdtJI5HhCT7UmmET2xVY7xlA1RqlBQdQl"
ACCESS_TOKEN_SECRET = "6ZRIqd9HDCgZxsR6iMUbt6eOgk1YVsz59lEsvL30eFnPf"
CONSUMER_KEY = "slWhR4Z6VOjp0R3ojx1B2a4pr"
CONSUMER_SECRET = "6OrySqqUIwQM8ioBycqbStWizM6KkLCMFecjXPvbVmsrsw6eNT"
Count = 0
translator = Translator()
class StdOutListener(StreamListener):
def on_data(self, data):
global Count
#Data has the JSON STring
y = json.loads(data)
print("--------------------")
try:
y = y['extended_tweet']['full_text']
y = str(y)
## Portuguese to English conversion block
translations = translator.translate(y, dest='en')
print(translations.origin, '\n -> \n', translations.text)
z = translations.text
a = translations.origin
row = [data,a,z]
with open(fetched_tweets_filename, 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
Count = Count + 1
print(Count)
except KeyError:
y = y['text']
y = str(y)
## Portuguese to English conversion block
translations = translator.translate(y, dest='en')
print(translations.origin, '\n -> \n', translations.text)
z = translations.text
a = translations.origin
row = [data,a,z]
with open(fetched_tweets_filename, 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
Count = Count + 1
print(Count)
### Sentiment Analysis block
analysis = TextBlob(z)
if analysis.sentiment.polarity > 0:
print("sentiment is positiv")
elif analysis.sentiment.polarity == 0:
print("sentiment is Neutral")
else:
print("sentiment is Negative")
print("--------------------\n")
return True
def on_error(self,status):
print(status)
if __name__ == "__main__":
listener=StdOutListener()
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
fetched_tweets_filename = "datas3.csv"
stream = Stream(auth, listener)
stream.filter(track=['como'],languages=['pt'])
引文
--------------------
RT @VBrasil_: Você decidiu chamar todos os meninos para assistir um filme na sua casa! Mas como cada um queria assistir algo, vocês decidir…
->
RT @VBrasil_: You decided to call all the boys to watch a movie in your house! But as everyone wanted to watch something, you decide ...
1
sentiment is Neutral
--------------------
--------------------
RT @queroqtefodas2: Como é ter uma turma unida ?
->
RT @myselfs: What is it like to have a group together?
2
sentiment is Neutral
--------------------
--------------------
RT @thiegonovais: FUTURO AMEAÇADO?
Entenda como é importante os fãs de Harry Potter se unirem mais do que nunca. Isso pode impactar tudo!…
->
RT @thiegonovais: FUTURE THREATENED?
Understand how important it is for Harry Potter fans to come together more than ever. This can impact everything! ...
3
sentiment is positiv
--------------------
--------------------
RT @nadiardgs: como assim você OUSA seguir no Instagram a conta do meu namorado de 27 anos desempregado streamer de lol e fã de Djonga?
tá…
->
RT @nadiardgs: how dare you follow on Instagram the account of my unemployed 27-year-old boyfriend lol streamer and Djonga fan?
OK…
4
sentiment is positiv
--------------------
--------------------
Amanda foi dormir na amiga dela, e eu fiquei sozinha como sempre.
->
Amanda went to bed with her friend, and I was alone as usual.
5
sentiment is Negative
--------------------
--------------------
Este é só um exemplo de "voto de cabresto" pelo interior do nosso Brasil. O @ptbrasil sabia fazer isto muito bem, entretanto...
->
This is just an example of a "halting vote" for the interior of our Brazil. @Ptbrasil knew how to do this very well, though ...
6
sentiment is positiv
--------------------
--------------------
E ainda tem gente que tira sarro de feminismo vtnc...
Com nossa luta há décadas ainda vemos notícias como essa diariamente, imagina sem!
->
And there are still people who make fun of vtnc feminism ...
With our struggle for decades we still see news like this every day, imagine without!
7
sentiment is positiv
--------------------
--------------------
RT @cvrlosmdz: Eu nem tenho palavras para quem quebra pinky promise smh como é que conseguem quebrar uma cena tão séria ? Oh pinky mm é a p…
->
RT @cvrlosmdz: I do not even have words for anyone who breaks pinky promise smh how can they break such a serious scene? Oh pinky mm is the p ...
8
sentiment is Negative
--------------------
--------------------
Se tem uma coisa que vou sentir saudade quando defender o mestrado é a refeição por 3 reais no RU, putz como eu amo pagar só treisss reaissssss numa refeição
QUANTO?
SÓ TREISSSSS REAISSSSS
->
If there is one thing I will miss when defending the masters is the meal for 3 reals in the UK, putz as I love to pay only real reals in a meal
HOW MUCH?
ONLY TREISSSSS REAISSSSS
9
sentiment is positiv
--------------------
--------------------
Estou doida p/ir pro cinema, porem cm o gato mas como eu não tenho kkk vai cm as manas mesmo!!!!
->
I'm crazy to go to the cinema, but the cat but I do not have kkk goes in the same manas !!!!
10
sentiment is Negative
--------------------
--------------------
#expedientefutebol futebol é assim, cabe ao jogador se portar como exemplo que é, e enquanto todos lamberem ele, irá continuar assim, e na seleção brasileira ele joga merda nenhuma
->
# football football is so, it's up to the player to be an example, and while everyone licks it, will continue like this, and in the Brazilian team he plays no shit
11
sentiment is positiv
--------------------
--------------------
KKKKKKKKKKK, nem como tanto assim
->
KKKKKKKKKKK, or how much
12
sentiment is positiv
--------------------
--------------------
Tô assistindo os vídeos antigos do Felipe Neto e lembrando de como eu era feliz
->
I'm watching Felipe Neto's old videos and remembering how happy I was
13
sentiment is positiv
--------------------
--------------------
a julia as vezes eh tao seca que qnd fala eu te amo eu fico boba
->
Julia sometimes it's so dry that you say I love you, I'm silly.
14
sentiment is Negative
--------------------
--------------------
RT @hellboyahs: gente me ajuda, como dizer para uma pessoa que não quer mais conversar com ela por ela ser chata mas sem magoar a pessoa?
->
RT @hellboyahs: People help me, how to tell a person who does not want to talk to her anymore because she is annoying but not hurting the person?
15
sentiment is Negative
--------------------
--------------------
@resistxre @CabelloJane458 Uai cada um tem sua opinião e tem pessoas que expressão sua opinião como vc expressou a sua . O RBR é uma produção tosca kkkkkkkkkkk da vergonha alheia pq poderia ser melhor a Record poderia fazer algo legal se não nem fizesse pra virar aquilo .
->
@resistxre @ CabelloJane458 Uai everyone has their opinion and has people who express their opinion as you expressed yours. The RBR is a crude production kkkkkkkkkkk of the shame of others could be better Record could do something cool if it did not even make it turn.
16
sentiment is positiv
--------------------
--------------------
RT @Bultaourune: Lembando que o BTS é o #1 Ato Coreano >NA HISTÓRIA< indicado a Top Duo/Group no BBMAs, also eles serão tb o #1 k-Ato a gan…
->
RT @Bultaourune: Remembering that the BTS is the # 1 Korean Act & NA HISTORY & lt; indicated the Top Duo / Group in the BBMAs, also they will be tb o # 1 k-Ato a gan ...
17
sentiment is positiv
--------------------
--------------------
Traceback (most recent call last):
File "C:\Users\ManoharRaoN\Desktop\SentizAnalyzer\Version3.py", line 85, in <module>
stream.filter(track=['como'],languages=['pt'])
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 453, in filter
self._start(is_async)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 368, in _start
self._run()
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 300, in _run
six.reraise(*exc_info)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\six.py", line 693, in reraise
raise value
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 269, in _run
self._read_loop(resp)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 331, in _read_loop
self._data(next_status_obj)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 303, in _data
if self.listener.on_data(data) is False:
File "C:\Users\ManoharRaoN\Desktop\SentizAnalyzer\Version3.py", line 48, in on_data
translations = translator.translate(y, dest='en')
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\googletrans\client.py", line 172, in translate
data = self._translate(text, dest, src)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\googletrans\client.py", line 81, in _translate
data = utils.format_json(r.text)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\googletrans\utils.py", line 62, in format_json
converted = legacy_format_json(original)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\site-packages\googletrans\utils.py", line 54, in legacy_format_json
converted = json.loads(text)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[Finished in 13.7s with exit code 1]
[shell_cmd: python -u "C:\Users\ManoharRaoN\Desktop\SentizAnalyzer\Version3.py"]
[dir: C:\Users\ManoharRaoN\Desktop\SentizAnalyzer]
[path: C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Webex\Webex\Applications;C:\Program Files\IBM\SPSS\Modeler\18.1.1\ext\bin\spss.TMWBServer\bin;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37;C:\Users\ManoharRaoN\AppData\Local\Programs\Python\Python37\Scripts;C:\Users\ManoharRaoN\AppData\Roaming\nltk_data;C:\Users\ManoharRaoN\AppData\Local\Microsoft\WindowsApps;C:\Users\ManoharRaoN\AppData\Local\Box\Box Edit\]
我认为它发生在某些推文上,当它发生时我该如何传递它。不确定我是否完全错误。
当我尝试编写包含特殊字符(例如“te amo ❤️”)的字符串时,我也会收到以下错误下面是错误
--------------------
RT @PortalMessi: “Messi seria para mim, como um jogador que eu vi jogar, o número 1. Meu pai sempre disse que o melhor foi Pelé, mas eu não…
->
RT @PortalMessi: "Messi would be for me, as a player I saw play, the number 1. My father always said that the best was Pele, but I did not ...
1
sentiment is positiv
--------------------
--------------------
RT @felipeneto: Informo que a dívida de 170 mil reais do Botafogo comigo como pessoa física foi integralmente perdoada, junto com os juros…
->
RT @felipeneto: I report that Botafogo's debt of 170,000 reais with me as a natural person has been totally forgiven, along with interest ...
2
sentiment is positiv
--------------------
--------------------
@MaluMonteiro08 óh @deus como pode tamanha beleza?????
->
@ MaluMonteiro08 ohh @deus how can such beauty ?????
3
sentiment is Neutral
--------------------
--------------------
Meu pai amava.
Descanse em paz, rainha! ❤️
->
My father loved it.
Rest in peace, queen! (I.e.
Traceback (most recent call last):
File "C:\Users\Stramzik\Desktop\SentizAnalyzer\Version3.py", line 32, in on_data
y = y['extended_tweet']['full_text']
KeyError: 'extended_tweet'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Stramzik\Desktop\SentizAnalyzer\Version3.py", line 84, in <module>
stream.filter(track=['como'],languages=['pt'])
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 453, in filter
self._start(is_async)
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 368, in _start
self._run()
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 300, in _run
six.reraise(*exc_info)
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\six.py", line 693, in reraise
raise value
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 269, in _run
self._read_loop(resp)
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 331, in _read_loop
self._data(next_status_obj)
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\site-packages\tweepy\streaming.py", line 303, in _data
if self.listener.on_data(data) is False:
File "C:\Users\Stramzik\Desktop\SentizAnalyzer\Version3.py", line 55, in on_data
writer.writerow(row)
File "C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 5967-5968: character maps to <undefined>
[Finished in 5.5s with exit code 1]
[shell_cmd: python -u "C:\Users\Stramzik\Desktop\SentizAnalyzer\Version3.py"]
[dir: C:\Users\Stramzik\Desktop\SentizAnalyzer]
[path: C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Webex\Webex\Applications;C:\Program Files\IBM\SPSS\Modeler\18.1.1\ext\bin\spss.TMWBServer\bin;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Users\Stramzik\AppData\Local\Programs\Python\Python37;C:\Users\Stramzik\AppData\Local\Programs\Python\Python37\Scripts;C:\Users\Stramzik\AppData\Roaming\nltk_data;C:\Users\Stramzik\AppData\Local\Microsoft\WindowsApps;C:\Users\Stramzik\AppData\Local\Box\Box Edit\]
最佳答案
import json
import csv
class StdOutListener(StreamListener):
def on_data(self, data):
global Count
#Data has the JSON STring
print("--------------------")
try:
y = json.loads(data)
y = y['extended_tweet']['full_text']
y = str(y)
## Portuguese to English conversion block
translations = translator.translate(y, dest='en')
print(translations.origin, '\n -> \n', translations.text)
z = translations.text.encode("utf-8")
a = translations.origin.encode("utf-8")
data = data.encode("utf-8")
row = [data,a,z]
with open(fetched_tweets_filename, 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
Count = Count + 1
print(Count)
except KeyError:
y = y.get('text', '') # change this to get
y = str(y)
## Portuguese to English conversion block
translations = translator.translate(y, dest='en')
print(translations.origin, '\n -> \n', translations.text)
z = translations.text.encode("utf-8")
a = translations.origin.encode("utf-8")
row = [data, a, z]
with open(fetched_tweets_filename, 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
Count = Count + 1
print(Count)
except Exception as e:
print(str(e))
### Sentiment Analysis block
analysis = TextBlob(z)
if analysis.sentiment.polarity > 0:
print("sentiment is positiv")
elif analysis.sentiment.polarity == 0:
print("sentiment is Neutral")
else:
print("sentiment is Negative")
print("--------------------\n")
return True
def on_error(self,status):
print(status)
if __name__ == "__main__":
listener=StdOutListener()
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
fetched_tweets_filename = "datas3.csv"
stream = Stream(auth, listener)
stream.filter(track=['como'],languages=['pt'])
关于python - 从 None 获取 "raise JSONDecodeError("Expecting value", s, err.value) json.decoder.JSONDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55911678/
最近开始学习MongoDB。今天老师教了我们 mongoexport 命令。在练习时,我遇到了一个典型的问题,包括教练在内的其他同学都没有遇到过。我在我的 Windows 10 机器上使用 Mongo
我是 JSON Schema 的新手,读过什么是 JSON Schema 等等。但我不知道如何将 JSON Schema 链接到 JSON 以针对该 JSON Schema 进行验证。谁能解释一下?
在 xml 中,我可以在另一个 xml 文件中包含一个文件并使用它。如果您的软件从 xml 获取配置文件但没有任何方法来分离配置,如 apache/ngnix(nginx.conf - site-av
我有一个 JSON 对象,其中包含一个本身是 JSON 对象的字符串。我如何反序列化它? 我希望能够做类似的事情: #[derive(Deserialize)] struct B { c: S
考虑以下 JSON { "a": "{\"b\": 12, \"c\": \"test\"}" } 我想定义一个泛型读取 Reads[Outer[T]]对于这种序列化的 Json import
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 11 个月前关闭。 Improve
我的旧项目在 MySQL 中有 Standard JSON 格式的数据。 对于我在 JS (Node.js) 和 DynamoDB 中的全新项目,关于 Standard JSON格式: 是否建议将其转
JSON 值字符串、数字、true、false、null 是否是有效的 JSON? 即,是 true 一个有效的 JSON 文档?还是必须是数组/对象? 一些验证器接受这个(例如 http://jso
我有一个 JSON 字符串,其中一个字段是文本字段。这个文本字段可以包含用户在 UI 中输入的文本,如果他们输入的文本是 JSON 文本,也许是为了说明一些编码,我需要对他们的文本进行编码,以便它不会
我正在通过 IBM MQ 调用处理数据,当由 ColdFusion 10 (10,0,11,285437) 序列化时,0 将作为 +0.0 返回,它会导致无效的 JSON并且无法反序列化。 stPol
我正在从三个数组中生成一个散列,然后尝试构建一个 json。我通过 json object has array 成功了。 require 'json' A = [['A1', 'A2', 'A3'],
我从 API 接收 JSON,响应可以是 30 种类型之一。每种类型都有一组唯一的字段,但所有响应都有一个字段 type 说明它是哪种类型。 我的方法是使用serde .我为每种响应类型创建一个结构并
我正在下载一个 JSON 文件,我已将其检查为带有“https://jsonlint.com”的有效 JSON 到文档目录。然后我打开文件并再次检查,结果显示为无效的 JSON。这怎么可能????这是
我正在尝试根据从 API 接收到的数据动态创建一个 JSON 对象。 收到的示例数据:将数据解码到下面给出的 CiItems 结构中 { "class_name": "test", "
我想从字符串转换为对象。 来自 {"key1": "{\n \"key2\": \"value2\",\n \"key3\": {\n \"key4\": \"value4\"\n }\n
目前我正在使用以下代码将嵌套的 json 转换为扁平化的 json: import ( "fmt" "github.com/nytlabs/gojsonexplode" ) func
我有一个使用来自第三方 API 的数据的应用程序。我需要将 json 解码为一个结构,这需要该结构具有“传入”json 字段的 json 标签。传出的 json 字段具有不同的命名约定,因此我需要不同
我想使用 JSON 架构来验证某些值。我有两个对象,称它们为 trackedItems 和 trackedItemGroups。 trackedItemGroups 是组名称和 trackedItem
考虑以下案例类模式, case class Y (a: String, b: String) case class X (dummy: String, b: Y) 字段b是可选的,我的一些数据集没有字
我正在存储 cat ~/path/to/file/blah | 的输出jq tojson 在一个变量中,稍后在带有 JSON 内容的 curl POST 中使用。它运作良好,但它删除了所有换行符。我知
我是一名优秀的程序员,十分优秀!