2017-03-08 5 views
0

私はこのPythonでは、辞書を検索して各行のテキストを置き換える方法は?

id details 
    1 I have an account 
    2 acnt is now closed 
    3 he knws my acc no 

のようなデータセットを持っており、各行が単語のリスト/文字列の場合、すべての単語を置き換えるために、どのように辞書

d ={'acc' : 'account', 'acnt' : 'account', 'knws':'knows'} 

を持っている場合は?また、データセットには50万行もあります。

出力はこの

id details 
    1 I have an account 
    2 account is now closed 
    3 he knows my account no 

答えて

0

これは、ブルートフォースの仕事であることを伝えたいと思います。まず、ファイルの行を読み、変更されたテキストを新しいファイルに書き込む必要があります。

テキストの各行について、辞書のすべてのキーを調べ、必要な置換えを行います。その部分は次のようになります。

for line in input_file: 
    for word in abbrev_dict: 
     if word in line: 
      line = line.replace(word, abbrev_dict[word]) 
    # write the altered line to the output file 

解決策に向かって動くのですか?

0

迅速かつ汚いアプローチ

with open('bigfile') as f: 
     for line in f: # iterate over each line and replace words with alias 
       print " ".join([d.get(w,w) for w in line.split(" ")] # your desired output 
関連する問題