2011-09-10 3 views
2

私は多くの単語のいくつかのスペルバリエーションを含むテキストファイルを持っています:Python:テキストファイルを正規化する

identification ... ID .. identity...contract.... contr.... contractor...medicine...pills..tables 

だから私は、言葉の同義語が含まれており、主要語で、すべての変種を交換したい同義語のテキストファイルを持っていると思います。基本的には、入力ファイルを正規化します。例えば、私の同義語リストファイルは

identification = ID identify 
contracting = contract contractor contractors contra...... 
word3 = word3_1 word3_2 word3_3 ..... word3_n 
. 
. 
. 
. 
medicine = pills tables drugs... 

のようになりますについては

私は最後の出力ファイルは、私はPythonでプログラミングについて得にはどうすればよい

identification ... identification .. identification...contractor.... contractor.... contractor...medicine...medicine..medicine 

見えるようにしたいですか?

ありがとうございました!

答えて

3

を見て:

import re 

table={} 
with open('synonyms','r') as syn: 
    for line in syn: 
     match=re.match(r'(\w+)\s+=\s+(.+)',line) 
     if match: 
      primary,synonyms=match.groups() 
      synonyms=[synonym.lower() for synonym in synonyms.split()] 
      for synonym in synonyms: 
       table[synonym]=primary.lower() 

print(table) 

利回り

{'word3_1': 'word3', 'word3_3': 'word3', 'word3_2': 'word3', 'contr': 'contracting', 'contract': 'contracting', 'contractor': 'contracting', 'contra': 'contracting', 'identify': 'identification', 'contractors': 'contracting', 'word3_n': 'word3', 'ID': 'identification'} 

次に、テキストファイルを読み込み、そしてtableから、その主同義語で各単​​語を置き換えることができます:

with open('textfile','r') as f: 
    for line in f: 
     print(''.join(table.get(word.lower(),word) 
         for word in re.findall(r'(\W+|\w+)',line))) 

利回り

identification  identification identity contracting  contracting  contracting medicine medicine medicine 

  1. re.findall(r'(\w+|\W+)',line)は、各lineしばらくの分割を使用しました 空白を保持します。空白に問題がなければ、 でも簡単に使用できますline.split()
  2. table.get(word,word)戻りtable[word]言葉は、tableである 単にwordは同義語tableにない場合wordを返す場合。
+0

空白区切りでは、「あなたのIDを表示する」のように、末尾に句読点が追加されます。空白文字で分割した場合、 "ID"に変換するきれいな "ID"文字列は得られません。大文字/小文字も処理する必要があります。 – PaulMcG

+1

@Paul McGuire:コメントをいただきありがとうございます。単語から句読点を区切るために '\ s + | \ S +'を '\ w + | \ W +'に変更し、大文字小文字を扱うコードを追加しました。 @Pradeep:これらの変更は起こりそうもないかもしれませんが、同義語リストの句読点付きの単語(「can't」のような)はもはやマッチしなくなり、大文字と小文字の区別がついた単語(ポーランド語は国籍ですが、 'は動詞です)が同じ同義語に置き換えられる可能性があります。これらの問題は、より多くのコードで処理することができますが、それがあなたの状況に影響を及ぼさない限り、そうしないでください。 – unutbu

+0

Paulありがとうございます。あなたのコードは意図どおりに動作します.. – Zenvega

3

だけの思考:その代わり、単語のすべて変動のリストを持つのはtable、あなたは同義語ファイルを読み込み、辞書に変換することができdifflib

>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) 
['apple', 'ape'] 
>>> import keyword 
>>> get_close_matches('wheel', keyword.kwlist) 
['while'] 
>>> get_close_matches('apple', keyword.kwlist) 
[] 
>>> get_close_matches('accept', keyword.kwlist) 
['except'] 
+0

ありがとうございます。このタイプのヒューリスティックがスクラビングに必要です。私は、私が取り組んでいるアプリケーションのやや高度な段階でこれを調べるつもりです。 – Zenvega

関連する問題