2017-03-20 12 views
-1

HTMLページから生のテキストを取得するタスクがあります。 HTMLの解析の後、たくさんの '\ n'記号を含む文字列を受け取ります。それを空に置き換えようとすると、replace関数が機能しません。python3のreplace()が長い文字列では機能しない

from bs4 import BeautifulSoup 
import urllib 
with urllib.request.urlopen('http://shakespeare.mit.edu/lear/full.html') as response: 
lear_bytes = response.read() 
lear_html = str(lear_bytes) 
soup = BeautifulSoup(lear_html, 'html.parser') 
lear_txt_dirty = soup.get_text() 
lear_txt_clean = str.replace(lear_txt_dirty, '\n', '') 
print(lear_txt_clean) 
+0

[mcve]を作成できますか? –

+0

@ Jean-FrançoisFabreインデントエラーを修正した後、このコードが実行され、問題を示すかどうか...それは本当に問題ではありません! – tdelaney

+0

@tdelaney Pythonのreplace関数は機能しますか?私はすっごく安心しています。 –

答えて

1

文字列の問題を整理あなたが本当にそこに何を見ることができるように、その有用なのは、文字列のreprを印刷する:ここに私のコードです。あなたの印刷の交換:

#print(lear_txt_clean) 
print("Num newlines", lear_txt_clean.count('\n')) 
print(repr(lear_txt_clean[:80])) 

私はあなたがテキストではなく、実際のテキストのPythonのバイト表現を処理している

Num newlines 0 
"b'\\n \\n \\n King Lear: Entire Play\\n \\n \\n \\n \\n \\n\\n\\nKing Lear\\n\\n  Shakesp" 

を取得します。あなたのコードでlear_bytesbytesオブジェクトですが、lear_html = str(lear_bytes)はオブジェクトをデコードしません。これはbytesオブジェクトのpython表現を提供します。代わりに、BeautifulSoupに生のバイトがあり、それを並べ替えることができます。

from bs4 import BeautifulSoup 
import urllib 
with urllib.request.urlopen('http://shakespeare.mit.edu/lear/full.html') as response: 
    soup = BeautifulSoup(response.read(), 'html.parser') 
lear_txt_dirty = soup.get_text() 
lear_txt_clean = str.replace(lear_txt_dirty, '\n', '') 
print(lear_txt_clean[:80]) 
+0

ありがとうございました!それは仕事です!また、私は、同じ結果を得ることが可能であることを認識しています。これは、strではなくdecodeメソッドを使ってlear_bytesに渡します。 –

関連する問題