python-----简单英文语料预处理

英文语料预处理的主要步骤:

(此步骤针对的是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)

至此,英文语料的简单的预处理就完成了,接下来可以进行想要的操作了。

 

 

你可能感兴趣的:(python-----简单英文语料预处理)