5

Python と BeautifulSoup の初心者。「example.html」というファイルを開き、BeautifulSoup アクションを実行し、次にブリーチ アクションを実行し、結果をファイル「example-cleaned.html」として保存する Python プログラムがあります。これまでのところ、「example.html」のすべてのコンテンツで機能しています。

フォルダー「/posts/」内の各ファイルを開き、その上でプログラムを実行し、「/posts-cleaned/X-cleaned.html」として保存するように変更する必要があります。X は元のファイル名です。

最小化された私のコードは次のとおりです。

from bs4 import BeautifulSoup
import bleach
import re

text = BeautifulSoup(open("posts/example.html"))
text.encode("utf-8")

tag_black_list = ['iframe', 'script']
tag_white_list = ['p','div']
attr_white_list = {'*': ['title']}

# Step one, with BeautifulSoup: Remove tags in tag_black_list, destroy contents.
[s.decompose() for s in text(tag_black_list)]
pretty = (text.prettify())

# Step two, with Bleach: Remove tags and attributes not in whitelists, leave tag contents.
cleaned = bleach.clean(pretty, strip="TRUE", attributes=attr_white_list, tags=tag_white_list)

fout = open("posts/example-cleaned.html", "w")
fout.write(cleaned.encode("utf-8"))
fout.close()
print "Done"

喜んで受け取った既存のソリューションへの支援と指針!

4

2 に答える 2

5

os.listdir()ディレクトリ内のすべてのファイルのリストを取得するために使用できます。ディレクトリツリーをずっと再帰したい場合は、os.walk().

このコードをすべて移動して、単一のファイルを処理し、ディレクトリ全体の解析を処理する 2 つ目の関数を記述します。このようなもの:

def clean_dir(directory):

    os.chdir(directory)

    for filename in os.listdir(directory):
        clean_file(filename)

def clean_file(filename):

    tag_black_list = ['iframe', 'script']
    tag_white_list = ['p','div']
    attr_white_list = {'*': ['title']}

    with open(filename, 'r') as fhandle:
        text = BeautifulSoup(fhandle)
        text.encode("utf-8")

        # Step one, with BeautifulSoup: Remove tags in tag_black_list, destroy contents.
        [s.decompose() for s in text(tag_black_list)]
        pretty = (text.prettify())

        # Step two, with Bleach: Remove tags and attributes not in whitelists, leave tag contents.
        cleaned = bleach.clean(pretty, strip="TRUE", attributes=attr_white_list, tags=tag_white_list)

        # this appends -cleaned to the file; 
        # relies on the file having a '.'
        dot_pos = filename.rfind('.')
        cleaned_filename = '{0}-cleaned{1}'.format(filename[:dot_pos], filename[dot_pos:])

        with open(cleaned_filename, 'w') as fout:
            fout.write(cleaned.encode("utf-8"))

    print "Done"

次に、電話clean_dir('/posts')するかどうかだけです。

ファイルに「-cleaned」を追加していますが、まったく新しいディレクトリを使用するというあなたの考えが気に入っていると思います. そうすれば-cleaned、ファイルなどに既に存在する場合に競合を処理する必要がなくなります。

また、ステートメントを使用して、withファイルを閉じて例外を自動的に処理するため、ここでファイルを開きます。

于 2012-10-22T17:11:25.627 に答える
2

os.listdir の Python ドキュメントが少し役に立たないと思うかもしれない他の人のために、私自身の質問に答えてください:

from bs4 import BeautifulSoup
import bleach
import re
import os, os.path

tag_black_list = ['iframe', 'script']
tag_white_list = ['p','div']
attr_white_list = {'*': ['title']}

postlist = os.listdir("posts/")

for post in postlist: 

        # HERE: you need to specify the directory again, the value of "post" is just the filename:
    text = BeautifulSoup(open("posts/"+post))
    text.encode("utf-8")

    # Step one, with BeautifulSoup: Remove tags in tag_black_list, destroy contents.
    [s.decompose() for s in text(tag_black_list)]
    pretty = (text.prettify())

    # Step two, with Bleach: Remove tags and attributes not in whitelists, leave tag contents.
    cleaned = bleach.clean(pretty, strip="TRUE", attributes=attr_white_list, tags=tag_white_list)

    fout = open("posts-cleaned/"+post, "w")
    fout.write(cleaned.encode("utf-8"))
    fout.close()

「posts-cleaned/」という名前の別のフォルダーをだまして作成しました。ファイルを保存する方が、ファイル名を分割して「cleaned」を追加し、再度結合するよりも簡単だったからです。 、それはさらに良いでしょう。

于 2012-10-22T17:04:33.197 に答える