2016-06-08 1 views
0
# -*- coding: utf-8 -*- 
from __future__ import print_function 
import os, codecs, re, string, mysql 
import mysql.connector 

'''Reading files with txt extension''' 
y_ = "" 
for root, dirs, files in os.walk("/Users/Documents/source-document/part1"): 
    for file in files: 
     if file.endswith(".txt"): 
      x_ = codecs.open(os.path.join(root,file),"r", "utf-8-sig") 
      for lines in x_.readlines(): 
       y_ = y_ + lines 
#print(tokenized_docs) 

'''Tokenizing sentences of the text files''' 

from nltk.tokenize import sent_tokenize 
raw_docs = sent_tokenize(y_) 

tokenized_docs = [sent_tokenize(y_) for sent in raw_docs] 

'''Removing stop words''' 

stopword_removed_sentences = [] 
from nltk.corpus import stopwords 
stopset = stopwords.words("English") 
for i in tokenized_docs[0]: 
    tokenized_docs = ' '.join([word for word in i.split() if word not in stopset]) 
    stopword_removed_sentences.append(tokenized_docs) 

''' Removing punctuation marks''' 

regex = re.compile('[%s]' % re.escape(string.punctuation)) #see documentation here: http://docs.python.org/2/library/string.html 
nw = [] 
for review in stopword_removed_sentences: 
    new_review = '' 
    for token in review: 
     new_token = regex.sub(u'', token) 
     if not new_token == u'': 
      new_review += new_token 
    nw.append(new_review) 

'''Lowercasing letters after removing puctuation marks.''' 

lw = [] #lw stands for lowercase word. 
for i in nw: 
    k = i.lower() 
    lw.append(k) 

'''Removing number with a dummy symbol''' 
nr = [] 
for j in lw: 
    string = j 
    regex = r'[^\[\]]+(?=\])' 
# let "#" be the dummy symbol 
    output = re.sub(regex,'#',string) 
    nr.append(output) 
nrfinal = []  
for j in nr: 
    rem = 0 
    outr = '' 
    for i in j: 
     if ord(i)>= 48 and ord(i)<=57: 
      rem += 1 
      if rem == 1: 
       outr = outr+ '#' 
     else: 
      rem = 0    
      outr = outr+i 
    nrfinal.append(outr) 

'''Inserting into database''' 
def connect(): 
    for j in nrfinal: 
     conn = mysql.connector.connect(user = 'root', password = '', unix_socket = "/tmp/mysql.sock", database = 'Thesis') 
     cursor = conn.cursor() 
     cursor.execute("""INSERT INTO splitted_sentences(sentence_id, splitted_sentences) VALUES(%s, %s)""",(cursor.lastrowid,j)) 
     conn.commit() 
     conn.close() 
if __name__ == '__main__': 
    connect() 

이 코드에는 어떤 오류도 표시되지 않습니다. 그것은 텍스트 파일을 위해 잘하고 있습니다. 문제는 프로그램에 너무 많은 시간이 걸리는 많은 텍스트 파일 (거의 6GB)이 있기 때문에 실행 시간에만 문제가 있습니다. 검사에서 나는 그것이 CPU 바인딩 된 것으로 나타났습니다. 따라서이를 해결하기 위해서는 다중 처리가 필요합니다. 병렬 처리가 가능하도록 다중 처리 모듈로 코드 작성을 도와주십시오. 감사합니다.어떻게 파이썬의 다중 처리 모듈을 사용하여 프로그램을 작성할 수 있습니까?

from multiprocessing import Pool 
def f(x): 
    return x*x 

if __name__ == '__main__': 
    with Pool(5) as p: 
     print(p.map(f, [1, 2, 3])) 

당신은 당신의 코드를 적용하려면이 옵션을 사용할 수 있습니다

+0

멀티 프로세싱 --- 리팩토링을 사용하기 전에 코드에 약점이 있습니다. – Merlin

+0

코드가 작동하기 때문에 http://codereview.stackexchange.com/ – Merlin

+0

에 게시하십시오. @Merlin OP가 아직 작성되지 않은 코드에 대해 질문하고 있으므로 CR에서 주제를 벗어났습니다. – Heslacher

답변

1

multiprocessing의 사용을 보여 python docs에서 예를 들어이있다. 텍스트 파일을 가져 오면 map 함수를 사용하여 나머지를 병렬로 실행합니다. 여러 코어에서 실행하려는 코드를 캡슐화하는 함수를 정의해야합니다.

그러나 파일을 병렬로 읽으면 성능이 저하 될 수 있습니다. 또한 비동기 적으로 데이터베이스에 내용을 추가해도 작동하지 않을 수 있습니다. 따라서 메인 스레드에서이 두 가지 작업을 수행하고 싶을 수도 있습니다.

관련 문제