2017-02-27 78 views
1

替換拋出錯誤我對Python非常陌生,我試圖理解和使用在Python 3.5.2上運行的Anaconda中的this link腳本。我不得不改變一些東西,以便腳本可以在此版本的Python中運行,因爲它是從2013年開始的。腳本(經驗不足的我修改)如下,我的問題在html = f.read().replace("</html>", "") + "</html>"行中的try塊中。替換「</html>」

我根本無法理解的+ "</html>"的右括號後到來的原因。從我在replace()方法中發現的情況來看,它至少需要兩個參數,即舊字符和新字符。實際上,此腳本跳轉到except Exception as e:並打印出a bytes-like object is required, not 'str'

現在,這是,據我所知道的,因爲閱讀被作爲字節完成,而替代方法接受字符串。我試圖將線劃分爲:

html = f.read 
html = str.replace("</html>", "") + "</html>" 

但是這會拋出replace() takes at least 2 arguments (1 given)。我也試着從bytes改變html的內容str如下

html = str(f.read(), 'utf-8') 
html = str.replace("</html>", "") 

但這也返回錯誤replace() takes two arguments (1 given)。當我完全刪除了html = str.replace("</html>", "") + "</html>"所以跳過的soup = BeautifulSoup(html),我結束了一個警告,沒有解析器明確規定,後來在一個AttributeError是NoneType object has no attribute get_dictionary

大約需要提及的線,以及爲什麼使用它,以及如何使用它任何幫助將不勝感激。謝謝。

#!/usr/bin/python 

import sys 
import urllib.request 
import re 
import json 

from bs4 import BeautifulSoup 

import socket 

socket.setdefaulttimeout(10) 

cache = {} 

for line in open(sys.argv[1]): 
fields = line.rstrip('\n').split('\t') 
sid = fields[0] 
uid = fields[1] 

# url = 'http://twitter.com/%s/status/%s' % (uid, sid) 
# print url 
tweet = None 
text = "Not Available" 
if sid in cache: 
    text = cache[sid] 
else: 
    try: 
     f = urllib.request.urlopen("http://twitter.com/%s/status/%s" % (uid, sid)) 
     print('URL: ', f.geturl()) 
     # Thanks to Arturo! 
     # html = f.read() 
     html = f.read().replace("</html>", "") + "</html>" 
     soup = BeautifulSoup(html) 
     jstt = soup.find_all("p", "js-tweet-text") 
     tweets = list(set([x.get_text() for x in jstt])) 
     # print len(tweets) 
     # print tweets 
     if (len(tweets)) > 1: 
      continue 

     text = tweets[0] 
     cache[sid] = tweets[0] 

     for j in soup.find_all("input", "json-data", id="init-data"): 
      js = json.loads(j['value']) 
      if js.has_key("embedData"): 
       tweet = js["embedData"]["status"] 
       text = js["embedData"]["status"]["text"] 
       cache[sid] = text 
       break 
    except Exception as e: 
     print(e) 
     # except Exception as e: 
     continue 

    if tweet is not None and tweet["id_str"] != sid: 
     text = "Not Available" 
     cache[sid] = "Not Available" 
    text = text.replace('\n', ' ',) 
    text = re.sub(r'\s+', ' ', text) 
    # print json.dumps(tweet, indent=2) 
    print("\t".join(fields + [text]).encode('utf-8')) 

回答

2

str.replace在其靜態形式使用replace(呼叫從str類型級,而不是一個對象str方法)。

str.replace實際上需要參數:要作用的字符串,要替換的字符串或字符串以及新的字符或字符串。

'abcd'.replace('d', 'z')被equivallent到str.replace('abcd', 'd', 'z')

print('abcd'.replace('d', 'z')) 
# abcz 
print(str.replace('abcd', 'd', 'z')) 
# abcz 
+0

感謝您的快速輸入。在你回覆之後,我把這行改爲了'html = str.replace(str(f.read(),'utf-8'),「」,「」)'並且它工作正常。如果js.has_key(「embedData」):'我在'if..statement'閱讀中還遇到另一個錯誤。由於在Python 3中已經刪除了has_key,所以我將它改爲讀取'if'embedData'in js:'。我將嘗試添加寫出來的文件併發布整個工作腳本。 – salvu

0

我已經接受了@DeepSpace好心給出一個答案的解決方案,它幫助我認識到如何克服我所面臨的問題。下面的代碼現在可以的Python 3下執行,如果從命令提示符下運行如下(請注意,我這個執行從Windows命令提示符):

python download_tweets.py inpuot_file.tsv > output_file.tsv。代碼如下:

#!/usr/bin/python 

import sys 
import urllib.request 
import re 
import json 

from bs4 import BeautifulSoup 

import socket 

socket.setdefaulttimeout(10) 

cache = {} 

for line in open(sys.argv[1]): 
    fields = line.rstrip('\n').split('\t') 
    sid = fields[0] 
    uid = fields[1] 

    tweet = None 
    text = "Not Available" 
    if sid in cache: 
     text = cache[sid] 
    else: 
     try: 
      f = urllib.request.urlopen("http://twitter.com/%s/status/%s" % (uid, sid)) 
      # print('URL: ', f.geturl()) 
      # Thanks to Arturo! 
      html = str.replace(str(f.read(), 'utf-8'), "</html>", "") 
      # html = f.read().replace("</html>", "") + "</html>" # original line 
      soup = BeautifulSoup(html, "lxml") # added "lxml" as it was giving warnings 
      jstt = soup.find_all("p", "js-tweet-text") 
      tweets = list(set([x.get_text() for x in jstt])) 
      # print(len(tweets)) 
      if (len(tweets)) > 1: 
      continue 

      text = tweets[0] 
      cache[sid] = tweets[0] 

      for j in soup.find_all("input", "json-data", id="init-data"): 
       js = json.loads(j['value']) 
       if "embedData" in js: 
       # if js.has_key("embedData"): # original line 
       tweet = js["embedData"]["status"] 
       text = js["embedData"]["status"]["text"] 
       cache[sid] = text 
       break 
     except Exception as e: 
      print(e) 
      continue 

     if tweet is not None and tweet["id_str"] != sid: 
      text = "Not Available" 
      cache[sid] = "Not Available" 
     text = text.replace('\n', ' ',) 
     text = re.sub(r'\s+', ' ', text) 
     # print(json.dumps("dump: ", tweet, indent=2)) 
     print(" \t ".join(fields + [text]).encode('utf-8'))