【发布时间】:2015-10-30 03:32:54
【问题描述】:
这是我第一次做文本挖掘项目并使用 Panda。我正在尝试收集下载的实时推文(json格式)中“文本”标签中的所有字符串,这样我就可以对所有推文进行标记并计算高频词。这是 json 格式的示例推文:
{
"contributors": null,
"truncated": false,
"text": "Hey Don : TheCougCoach :) Want to get iPh0ne 6 for FREE? Kindly check my bi0. Thx https://t.co/c38b8vqq2O",
"is_quote_status": true,
"in_reply_to_status_id": null,
"id": 659549062023262209,
"favorite_count": 0,
...... skip
},
"quoted_status_id": 659548944251228160,
"retweeted": false,
"coordinates": null,
"timestamp_ms": "1446083724872",
"quoted_status": {
"contributors": null,
"truncated": false,
"text": "I understand He is a criminal but Donald has all the right to be in the discussion. https://t.co/qv3oScGA1U",
"is_quote_status": true,
"in_reply_to_status_id": null,
这是我的代码(Python 2.7 + panda 0.17.0):
import json
import pandas as pd
tweets_data_path = 'tweet.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweets = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
print tweets['text']
print tweets['text'].astype(str) # Try to convert the panda series into strings so I can tokenize the tweets (strings after "text" in the json format) using regular expression
这是输出
0 Hey Don : TheCougCoach :) Want to get iPh0ne 6...
1 I understand He is a criminal but Donald has a...
Name: text, dtype: object
UnicodeEncodeError: 'ascii' codec can't encode characters in position 125-126: ordinal not in range(128)
两个问题:
(1) 推文 = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
这里 panda 与 map/lambda 一起提供了一种简单的方法来获取推文 json 文件中“文本”之后的数据。但是,“map”只允许匹配长度的列表,使得输出不完整(以 ... 结尾)。有没有更好的编码方式?
(2)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 125-126: ordinal not in range(128)
输入“tweet.txt”似乎是 unicodes,所以我们遇到了错误?如果是,我们是否应该在阅读“tweet.txt”时对其进行编码?实际的输入文件非常大(几 GB 甚至更大),那么有没有更有效的方法来解决这个问题?谢谢。
【问题讨论】:
标签: python list python-2.7 ascii tweets