2016-09-14 20 views
1

RegExを使用して出力をtxtファイルに出力するには、次のコードを使用しています。RegExをtxtファイルに書き込む

File "C:\lib\re.py", line 213, in findall 
return _compile(pattern, flags).findall(string) 

はTypeError例外:期待される文字列またはバイトのようなオブジェクト

import glob 
import os 
import re 


def extractor(): 
    os.chdir(r"F:\Test") 
    for file in glob.iglob("*.html"): # iterates over all files in the directory ending in .html 
     with open(file, encoding="utf8") as f, open((file.rsplit(".", 1)[0]) + ".txt", "w") as out: 
      contents = f.read() 
      extract = re.compile(r'RegEx', re.I | re.S) 
      if re.findall(extract, contents) is not None: 
       for x in re.findall(extract, contents): 
        out.write(x) 
      out.close() 
extractor() 

誰でもこのエラーを引き起こすもののアイデアをしかし、私は常に、このエラーメッセージが表示されますか?どうやらそれは型エラーと関係がありますか?

+0

're.findall(r'RegEx '、re.I | re.S)'の代わりに 're.compile(r'RegEx'、re.I | re.S)'を使用してください。 'contents'から何かを抽出する前に正規表現をコンパイルする必要があります。 –

+0

私のコード行 "out.write()"にもエラーメッセージが表示されます。 TypeError:write()引数は_sreではなくstrでなければなりません.REREPattern –

+0

はい、 'extract'は正規表現オブジェクトなので、そこにre.findallの結果を書く必要があります。パターンに複数のキャプチャ・グループがある場合は、 're.findall(extract、contents):xはout.write(x)'で、またはタプルを連結します。 –

答えて

0

微調整:

import glob 
import os 
import re 


def extractor(): 
    # you only need it once, dont' you? 
    extract = re.compile(r'RegEx', re.I | re.S) 
    os.chdir(r"F:\Test") 
    for file in glob.iglob("*.html"): # iterates over all files in the directory ending in .html 
    with open(file, encoding="utf8") as f, open((file.rsplit(".", 1)[0]) + ".txt", "w") as out: 
     contents = f.read() 
     for match in extract.findall(contents): 
      out.write(match) 
     out.close() 

extractor() 

これは、オブジェクトとしてextract使用しても、あなたのループ内if not Noneチェックを必要としません。
まだ動作していない場合は、実際の正規表現(いくつかのグループなどありますか?)を詳しく説明してください。

+0

あなたの助けに感謝します。残念ながら、pycharmはまだ私にエラーメッセージを与えます:TypeError:write()引数はタプルではなく、strでなければなりません。私のコードを更新して、あなたは私のRegExを見ることができますが、それは正常でなければなりません。 –

+0

Chatraumには誰もいませんか?ダンカーンの娘ダンは、私の娘だったのですか? –

+0

は戦争ダスンジェラードでしたか? –

関連する問題