2017-02-22 5 views
0

私はスクリプトを書くためにpythonを使って、html内の特定のパターン化されたテキストを削除しようとしました。しかし、私のコードは動作していないようです。Pythonを使ってhtmlからパターン化されたテキストを削除する

import os, re 

cwd = os.getcwd() 
print ('Now you are at this directory: \n' + cwd) 

# find files that have an extension with HTML 
Files = os.listdir(cwd) 
print Files 

def func(file): 
    for file in os.listdir(cwd): 
     if file.endswith('.html'): 
      for line in open(file): 
       re.sub(r'<strong>.*?<\/strong>', '', line) 
       # I feel the above line has some problems 
func(file) 

ありがとうございます!

答えて

2

あなたはエスケープする必要はありません。 \/は、実際はちょうど普通の/です。完全な参考文献については、the re documentationの紹介を参照してください。

あなたの正規表現は次のようになります。r'<strong>.*?</strong>'

しかし、正規表現でHTMLを解析することは推奨されません。それについてはBeautifulSoupを参照してください!

line = '<p>some text, <strong>SOME STRONG TEXT </strong> and again <strong>STONG TEXT</strong></p>' 
re.sub(r'<strong>.*?<\/strong>', '', line) 
#'<p>some text, and again </p>' 
+0

ありがとうThierry、私は間違いなくbeautifulsoupをチェックします!正規表現の場合、私は両方のパターンを試しましたが、どちらも動作しません...オリジナルのスクリプトを使用して、一致するテキストを印刷しようとすると、実際には正しくなります。私は一致した文字列を置き換えることを妨げるコードでどの部分が間違っているのか分かりません... – Penny

1

import os, re 

cwd = os.getcwd() 
print ('Now you are at this directory: \n' + cwd) 

# find files that have an extension with HTML 
Files = os.listdir(cwd) 

def func(file): 
    for file in os.listdir(cwd): 
     if file.endswith('.html'): 
       f = open(file, "r+") 
       text = re.sub(r'\<strong\>.*\<\/strong\>',"",f.read()) 
       f.close() 
       f = open(file, "w") 
       f.write(text) 
       f.close() 
func(file) 
+0

ありがとうございました!私の場合、私はさらに試してみる必要があります - 美しいスープがもっと役立つかどうかを見てください。 :) – Penny

関連する問題