Pythonを使用してWebサイトからテキストを取得し、そのテキストを使用して.txtファイルを作成しようとしています。私はBeautifulSoup4とRequestsを使用してサイトから情報を取得しています。テキストをプルしてファイルを作成することはできますが、問題はありませんが、生成されたテキストをVSCodeで開くと、次のようになります。
�It�s the year 3486 of the Saint Origin calendar. I was dead for over a hundred years. Jiang Chen, my name is�Jiang Chen. Why have I been reborn after a hundred years?�
これをウェブサイトと比較すると、 は特定の句読点であると考えられていることがわかります。次に、以下を使用してみました。
text = text.replace(u"\u201c", '"')
二重引用符の一部を置き換えると、問題の一部しか解決されないため、多くの句読点が残り、同じ方法を使用してすべての句読点を見つけようとするのは現実的ではありません。
これを修正する方法はありますか?おそらく、使用したい文字の種類を強制しますか?
必要に応じて私のソースコードは次のとおりです。
# MODULES NEEDED:
from bs4 import BeautifulSoup
import requests
# Link from which we want the text:
link = "http://liberspark.com/read/dragon-marked-war-god/chapter-1"
# Getting the page's source code:
source = requests.get(link)
# Creating the BeautifulSoup object:
source = BeautifulSoup(source.content.decode("utf-8"), "html.parser")
# Finding the the div which holds the text:
container = source.find("div", class_="reader-content")
# Variable that will hold all the text:
text = ""
# Going through all the <p> tags in the container:
for p in container.find_all("p"):
text += str(p.text) + "\n\n"
text = text.replace(u"\u2019", "'")
with open("test.txt", "w") as file:
file.write(text)
フォーマットでtest.txt
書かれていないのでutf-8
、wb
フラグを使ってバイナリモードでファイルを書き、.encode('utf-8')
with open("test.txt", "wb") as file:
file.write(text.encode('utf-8'))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加