2016-12-15 6 views
0

のフォルダがあり、それぞれのフォルダがあり、それぞれに多くのテキストファイルが含まれています。私は5ワード特定の単語の前後に抽出する必要があり、次のコードは正常に動作します。Hazmでペルシア語のテキストを正規化する方法

問題は、テキストを正規化しなかったため、それ以上の文章が返されるということです。 ペルシア語には、テキストを正規化するためのhazmというモジュールがあります。どのように私はこのコードでそれを使うことができますか?正規化の例について

"ك"に変わります "ک"又は"ؤ" "はو" に変更すべきです。最初の2つは実際にアラビア語のアルファベットで使用されていたので、ペルシャ語です。コードを正規化しないと、第2の形式で書かれた単語が返され、第1の形式の単語は認識されません。アラビア語)。

import os 
from hazm import Normalizer 


def getRollingWindow(seq, w): 
    win = [next(seq) for _ in range(11)] 
    yield win 
    for e in seq: 
     win[:-1] = win[1:] 
     win[-1] = e 
     yield win 


def extractSentences(rootDir, searchWord): 
    with open("پاکت", "w", encoding="utf-8") as outfile: 
     for root, _dirs, fnames in os.walk(rootDir): 
      for fname in fnames: 
       print("Looking in", os.path.join(root, fname)) 
       with open(os.path.join(root, fname), encoding = "utf-8") as infile: 
        #normalizer = Normalizer() 
        #fname = normalizer.normalize(fname) 
        for window in getRollingWindow((word for line in infile for word in line(normalizer.normalize(line)).split()), 11): 
         if window[5] != searchWord: continue 
         outfile.write(' '.join(window)+ "\n") 

答えて

0

私はHazmでは動作しません。しかし、それはコードの一部を次のようにそれをあなたの自己を正規化するために、かなり簡単です。 (コードだけでペルシャ語の文字とアラビア文字を置き換える)

def clean_sentence(sentence): 
    sentence = arToPersianChar(sentence) 
    sentence = arToPersianNumb(sentence) 
    return sentence 


def arToPersianNumb(number): 
    dic = { 
     '١': '۱', 
     '٢': '۲', 
     '٣': '۳', 
     '٤': '۴', 
     '٥': '۵', 
     '٦': '۶', 
     '٧': '۷', 
     '٨': '۸', 
     '٩': '۹', 
     '٠': '۰', 
    } 
    return multiple_replace(dic, number) 


def arToPersianChar(userInput): 
dic = { 
    'ك': 'ک', 
    'دِ': 'د', 
    'بِ': 'ب', 
    'زِ': 'ز', 
    'ذِ': 'ذ', 
    'شِ': 'ش', 
    'سِ': 'س', 
    'ى': 'ی', 
    'ي': 'ی' 
} 
return multiple_replace(dic, userInput) 


def multiple_replace(dic, text): 
    pattern = "|".join(map(re.escape, dic.keys())) 
    return re.sub(pattern, lambda m: dic[m.group()], str(text)) 

ちょうどあなたがあなたの文書の各ラインを読み、clean_sentence()にそれを渡す必要があります。

def clean_all(document): 
    clean = '' 
    for sentence in document: 
     sentence = clean_sentence(sentence) 
     clean += ' \n' + sentence 
    return clean 
関連する問題