2017-02-01 16 views
0

У меня есть список списковUTF-8 Код ошибки UTF-8 в моем коде на Python. Они проявляются в виде буквального UTF-8

[[ "Из-за штормов в эти выходные, мы перенесли на Блуменфилд велопробег за февраль 26. Надежда увидеть вас там. \ XE2 \ x80 \ xa6 '"], [' В этот уикенд много солнца, воспользуйтесь Бийч-автобусом, который доставит вас из Холмов Вудленда до пляжа всего за $ \ xe2 \ x80 \ xa6 '], [" RT @LHansenLA: Вчера получил заглянуть внутрь @LAPPL @EagleandBadge новая установка для «Мемориальной стены« Конец часов ». Отдавая дань падению @LAPD w/\ xe2 \ x80 \ xa6 '"], [«Счастлив присоединиться к Art Sherman и Wings Over @Wendys, чтобы почтить ветеранов & 15 лет еженедельных встреч, организованных Рон и \ xe2 \ x80 \ xa6 '"], [« Присоединяйтесь ко мне на четвертой ежегодной велопробеге Blumenfield. Наслаждайтесь западной долиной на двух колесах. RSVP: «]]

Как вы можете видеть, списки, к сожалению, отображают буквальный UTF-8 вместо самих символов. В какой-то момент в моем коде, я кодировать в UTF-8

outtweets = [[str(tweet.text.encode("utf-8"))] for tweet in correct_date_tweet]    
      outtweets = [[stuff.replace("b\'", "")] for sublist in outtweets for stuff in sublist] 
      outtweets = [[stuff.replace('b\"', "")] for sublist in outtweets for stuff in sublist] 

Приведенный выше код все необходимое для того, чтобы удалить б префиксов. Они не могут быть в моих твитах, потому что я занимаюсь анализом машинного обучения и влияют на него.

Мой вопрос

Как заменить скрипт UTF-8 с реальными персонажами?

мне нужно кодировать его как-то, потому что я потянув твиты из (3 городов) х (50 должностных лиц) х (12 месяцев твитов для каждого), поэтому было бы невозможно неэффективно, чтобы попытаться вручную заменить их.

Код

import tweepy #https://github.com/tweepy/tweepy 

#Twitter API credentials 
consumer_key = "insert key here" 
consumer_secret = "insert key here" 
access_key = "insert key here" 
access_secret = "insert key here" 

#authorize twitter, initialize tweepy 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_key, access_secret) 
api = tweepy.API(auth) 



#!/usr/bin/env python 
# encoding: utf-8 

import tweepy #https://github.com/tweepy/tweepy 
import json 
import csv 
import datetime 
from datetime import datetime 
import os.path 
failed_accounts = [] 

def get_all_tweets(screen_name,mode): 

    #try: 
     #Twitter only allows access to a users most recent 3240 tweets with this method 

     #initialize a list to hold all the tweepy Tweets 
     alltweets = []  

     #make initial request for most recent tweets (200 is the maximum allowed count) 
     new_tweets = api.user_timeline(screen_name = screen_name,count=200) 

     #save most recent tweets 
     alltweets.extend(new_tweets) 

     #save the id of the oldest tweet less one 
     oldest = alltweets[-1].id - 1 
     i = 0 

     num_req = 0 
     #keep grabbing tweets until there are no tweets left to grab 
     while len(new_tweets) > 0: 

      #all subsiquent requests use the max_id param to prevent duplicates 
      new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest) 

      #save most recent tweets 
      alltweets.extend(new_tweets) 

      #update the id of the oldest tweet less one 
      oldest = alltweets[-1].id - 1 

      print ("...%s tweets downloaded so far" % (len(alltweets))) 


      num_req = num_req + 1 

      # makes further requests only if batch doesn't contain tweets beyond oldest limit 
      oldest_limit = datetime(2016, 1, 20,0,0,0) 



      x = 0 


      for tweet in new_tweets: 
       raw_date = tweet.created_at 
       if raw_date < oldest_limit: 
        x = 1 
       else: 
        continue 

      if x == 1: 
       break 

      #BSP this script is designed to just keep going. I want it to stop. 
      #i = i + 1 

      #if i == 10: 
      # break 




     print("Number of Tweet Request Rounds: %s" %num_req) 
     correct_date_tweet = [] 

     for tweet in alltweets: 
      raw_date = tweet.created_at 
      #date = datetime.strptime(raw_date, "%Y-%m-%d %H:%M:%S") 

      newest_limit = datetime(2017, 1, 20,0,0,0) 
      oldest_limit = datetime(2016, 1, 20,0,0,0) 

      if raw_date > oldest_limit and raw_date < newest_limit: 
       correct_date_tweet.append(tweet) 
      else: 
       continue 


     #transform the tweepy tweets into a 2D array that will populate the csv 
     if mode == "tweets only" or "instance file": 
      outtweets = [[str(tweet.text.encode("utf-8"))] for tweet in correct_date_tweet]    
      outtweets = [[stuff.replace("b\'", "")] for sublist in outtweets for stuff in sublist] 
      outtweets = [[stuff.replace('b\"', "")] for sublist in outtweets for stuff in sublist] 
      outtweets = [["1 ",stuff.replace('"', "")] for sublist in outtweets for stuff in sublist] 
      #outtweets = [["1 ",stuff] for sublist in outtweets for stuff in sublist] 
     else: 
      outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8"),tweet.retweet_count,tweet.favorite_count,len(tweet.entities.get("hashtags")),len(tweet.entities.get("urls")),len(tweet.entities.get("user_mentions"))] for tweet in correct_date_tweet]  

     #write the csv 
     if mode == "instance file": 
      with open(os.path.join(save_location,'%s.instance' % screen_name), mode ='w') as f: 
       writer = csv.writer(f) 
       writer.writerows(outtweets) 
     else: 
      with open(os.path.join(save_location,'%s.csv' % screen_name), 'w',encoding='utf-8') as f: 
       writer = csv.writer(f) 
       if mode != "tweets only": 
        writer.writerow(["id","created_at","text","retweets","favorites","hashtags","urls"])  
       writer.writerows(outtweets) 

     pass 
     print("Done with %s" % screen_name) 

get_all_tweets("BobBlumenfield","instance file") 

Update

На основании ответа, я попытался изменить одну из линий outtweets = [[tweet.text] for tweet in correct_date_tweet]

Но это не сработало, потому что она дает

--------------------------------------------------------------------------- 
UnicodeEncodeError      Traceback (most recent call last) 
<ipython-input-12-a864b5efe8af> in <module>() 
----> 1 get_all_tweets("BobBlumenfield","instance file") 

<ipython-input-9-d0b9b37c7261> in get_all_tweets(screen_name, mode) 
    104    with open(os.path.join(save_location,'%s.instance' % screen_name), mode ='w') as f: 
    105     writer = csv.writer(f) 
--> 106     writer.writerows(outtweets) 
    107   else: 
    108    with open(os.path.join(save_location,'%s.csv' % screen_name), 'w',encoding='utf-8') as f: 

C:\Users\Stan Shunpike\Anaconda3\lib\encodings\cp1252.py in encode(self, input, final) 
    17 class IncrementalEncoder(codecs.IncrementalEncoder): 
    18  def encode(self, input, final=False): 
---> 19   return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
    20 
    21 class IncrementalDecoder(codecs.IncrementalDecoder): 

UnicodeEncodeError: 'charmap' codec can't encode characters in position 64-65: character maps to <undefined> 
+1

Откуда вы получаете свой список списков? Через библиотеку Twitter? –

+1

Связано: [Что делает символ «b» перед строковым литералом?] (Http://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of -a-string-literal) – JosefZ

+0

@AlastairMcCormack да, это exceprt из одного из файлов, которые я загрузил. Я использую tweepy –

ответ

1

Удалить следующую линию:

outtweets = [[str(tweet.text.encode("utf-8"))] for tweet in correct_date_tweet] 

Вот почему:

  1. Вы кодировании в строку байтов. Следовательно, b.
  2. Вы используете str без определенной кодировки. В этом режиме вы получаете представление массива, включая типы, опять же, b и экранирование UTF-8.
  3. Не нужно кодировать в середине вашего кода. Кодировать только при записи в файл или в сеть (а не при печати). Редко вам нужно позвонить .encode() самостоятельно, если вы используете встроенный кодировщик open().

При использовании open() в текстовом режиме, как вы это делаете, всегда указывайте кодировку, поскольку она различна для каждой платформы.

Удалить все другие виды использования .encode() с вашего кода.

Теперь вы можете удалить другие строки, которые пытаются исправить вашу ошибку.

+0

Я не думаю, что это можно сделать. Хотя, возможно, мне не нужна строковая часть этой строки, мне нужна часть этой строки, потому что мне нужно выбрать только текст твита в список. Поэтому я попробовал 'outtweets = [[tweet.text] для tweet in correct_date_tweet]', но это не сработало, потому что для загрузки твитов вам нужен Unicode UTF-8 по какой-то причине. Я не понимаю, почему. Я отправил обновление с ошибкой. –

+0

Да - см. Мой пункт о всегда определении кодировки при использовании 'open()'. Вы находитесь в Windows - поэтому кодировка по умолчанию не UTF-8! Вы сделали это один раз, но не там, где вам это нужно. Pass 'encoding = 'utf-8'', когда вы используете' open() ' –

+0

Wow! Удивительно! Моя третья попытка получить ответ. Вы решили работать! Большое вам спасибо :) –

 Смежные вопросы

  • Нет связанных вопросов^_^