替換拋出錯誤我對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'))
感謝您的快速輸入。在你回覆之後,我把這行改爲了'html = str.replace(str(f.read(),'utf-8'),「