CSV文件考虑:写作阿拉伯语在使用Python 2.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import unicodecsv as csv
import pandas as pd
tweets_data = []
tweets_file = open('tweets.txt', "r")
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweets_file1 = open('tweets.csv', "wb")
tweets_file_writer = csv.writer(tweets_file1, encoding='utf-8')
tweets_file_writer.writerow(['location', 'time', 'user_id', 'text', 'hashtags', 'user_mentions'])
for i in tweets_data:
location = unicode(i[u'user'][u'location']).encode('utf-8')
time = unicode(i[u'created_at']).encode('utf-8')
user_id = unicode(i[u'user'][u'id']).encode('utf-8')
text = unicode(i[u'text']).encode('utf-8')
hashtag = i[u'entities'][u'hashtags']
hashtags = []
for j in hashtag:
print j[u'text']
hashtags.append(u''.join(j[u'text']).encode('utf-8'))
mention = i[u'entities'][u'user_mentions']
mentions = []
for j in mention:
mentions.append(unicode(j[u'screen_name']).encode('utf-8'))
tweets_file_writer.writerow([location, time, user_id, text, hashtags, mentions])
tweets_file1.close()
我写了这个代码使用tweepy刮一些阿拉伯语数据。
我的问题是在这条线 tweets_file_writer.writerow([location, time, user_id, text, hashtags, mentions])
时添加#标签列出它不会出现在阿拉伯语, 虽然其他通常出现的所有数据。
实施例:
在CSV文件我需要编写一个主题标签列表等:
[ 'مجلة_النجوم2', 'سهيله_بن_لشهب', 'souhilabenlachhab']
似乎像这样:
['\ xd9 \ X85 \ XD8 \ XAC \ xd9 \ X84 \ XD8 \ xa9_ \ XD8 \ XA7 \ xd9 \ X84 \ xd9 \ X8 6 \ xd8 \ xac \ xd9 \ x88 \ xd9 \ x852', '\ xd8 \ xb3 \ xd9 \ x87 \ xd9 \ x8a \ xd9 \ x84 \ xd9 \ x87_ \ xd8 \ xa8 \ xd9 \ x86_ \ xd9 \ x84 \ XD8 \ XB4 \ xd9 \的x87 \ XD8 \ xa8' , 'souhilabenlachhab']
另外,python 3的unicode支持比2.x更强大。除非你绝对坚持,否则不要写2.x。 – tdelaney
不幸的是它是一项作业任务 –
太糟糕了。你会认为老师会跟上这种类型的事情。这是一个字符串中的utf-8数据,所以问题在于它如何到达那里。我相信它实际上是在阅读json文档。尝试'tweets_file = codecs.open('tweets.txt',“r”,encoding =“utf-8”)'。 ...并让我知道如果这有效。 – tdelaney