python-----簡単な英語の語彙の前処理

2153 ワード

英語の語彙の前処理の主なステップ:
(この手順はtxt形式のファイルを対象とし、ファイルが他のフォーマットの場合はtxtファイルに変換してから操作する必要があります)
1、記号、数字、中国語など、英語以外の文字を除く
2、言葉を止める
 
具体的な実装(python具体的な実装):
1、英語以外の文字を削除する
pythonでreモジュールを使用して、英語以外の文字を判断および置換します.
reを使用します.compile()はtxtファイルの非英語文字に一致し、検索する文字を()に入れます.sub()を使用して、非英語文字を何に置き換えたいかを決定します.コードはスペースに置き換えられます.
# -*- coding: utf-8 -*-
import os
import re
import codecs


def replace_func(input_file):
    p1 = re.compile(r'-\{.*?(zh-hans|zh-cn):([^;]*?)(;.*?)?\}-')
    p2 = re.compile(r'[(][: @ . , ?!\s][)]')
    p3 = re.compile(r'[「『]')
    p4 = re.compile(r'[\s+\.\!\/_,$%^*(+\"\')]+|[+——()?【】“”!,。?、~@#¥%……&*()0-9 , : ; \-\ \[\ \]\ ]')
    outfile = codecs.open('std_' + input_file, 'w', 'utf-8')
    with codecs.open(input_file, 'r', 'utf-8') as myfile:
        for line in myfile:
            line = p1.sub(r' ', line)
            line = p2.sub(r' ', line)
            line = p3.sub(r' ', line)
            line = p4.sub(r' ', line)
            outfile.write(line)
    outfile.close()

def run():
    data_path = ''
    data_names = ['pubmed_result2007.txt']
    for data_name in data_names:
        replace_func(data_name)
        print('{0} has been processed !'.format(data_name))
if __name__ == '__main__':
    run()

2、言葉を止める
まず、非アクティブワードテーブル(ダウンロードアドレス:https://download.csdn.net/download/zzzzhy/10544362)を選択し、jiebaモジュールを使用して無効語のマッチングと削除を行い、outputファイルに書き込むだけです.
import jieba.analyse
# coding=utf-8
stopwords=[]
for word in open('/Users/Desktop/new/stopword.txt','r'):
    stopwords.append(word.strip())
article=open('/Users/Desktop/new/std_pubmed_result2007.txt','r').read()
words=jieba.cut(article,cut_all=False)
stayed_line=""
for word in words:
    if word not in stopwords:
        stayed_line+=word+" "
print (stayed_line)
w = open('/Users/Desktop/new/output.txt','w')
w.write(stayed_line)

これで,英語の語彙の簡単な前処理が完了し,次に所望の操作を行うことができる.