2015-02-07 5 views
0

У меня есть еще одна проблема с Python, создающая частотное распределение из текста, соответствующего предварительно определенному списку слов. Фактически, я работаю с более чем 100 000 текстовых файлов (каждый из которых составляет около 15 000 слов), которые я хочу просмотреть и соответственно сопоставлять с списком слов/выражений (vocabulary_dict) около 6000 записей. Результатом должен быть словарь всех этих записей, связанных с их частотой. Вот то, что я сейчас делаю:Распределение частоты слов/выражений - повышение производительности

sample text = "As the prices of U.S. homes started to falter, doubts arose throughout the global financial system. Banks became weaker, private credit markets stopped functioning, and by the end of the year it was clear that the world banks had sunk into a global recession." 

vocabulary_dict = ['prices', 'banks', 'world banks', 'private credit marktes', 'recession', 'global recession'] 

def list_textfiles(directory): 
    # Creates a list of all files stored in DIRECTORY ending on '.txt' 
    textfiles = [] 
    for filename in listdir(directory): 
     if filename.endswith(".txt"): 
      textfiles.append(directory + "/" + filename) 
    return textfiles 

for filename in list_textfiles(directory): 
    # inread each report as textfile, match tokenized text with predefined wordlist and count number of occurences of each element of that wordlist 
    sample_text = read_textfile(filename).lower() 
    splitted = nltk.word_tokenize(sample_text) 
    c = Counter() 
    c.update(splitted) 
    outfile = open(filename[:-4] + '_output' + '.txt', mode = 'w') 
    string = str(filename) # write certain part of filename to outfile 
    string_print = string[string.rfind('/')+1:string.find('-')] + ':' + string[-6:-4] + '.' + string[-8:-6] + '.' + string[-12:-8] 
    for k in sorted(vocabulary_dict): 
    # recognize if wordlist element consist of one or more tokens, accordingly find matching token length in text file (report) 
     spl = k.split() 
     ln = len(spl) 
     if ln > 1: 
      if re.findall(r'\b{0}\b'.format(k),sample_text): 
       vocabulary_dict[k.lower()] += 1 
     elif k in sample_text.split(): 
      vocabulary_dict[k.lower()] += c[k] 
    outfile.write(string_print + '\n') 
    # line wise write each entry of the dictionary to the corresponding outputfile including comapany name, fiscal year end and tabulated frequency distribution 
    for key, value in sorted(vocabulary_dict.items()): 
     outfile.write(str(key) + '\t' + str(value) + '\n') 
    outfile.close() 

# Output accoring to the above stated example should be in the form: 
"selected part of filename (=string1)" 
'prices' 1 
'banks' 2 
'world banks' 1 
'private credit marktes' 1 
'recession' 1 
'global recession' 1 

код работает довольно хорошо, я все еще думаю, что есть место для оптимизации, так как время, чтобы обработать текстовый файл составляет около 1 минута. Мой вопрос: есть ли способ быстрее скопировать соответствие текста в список слов/выражений? Большое спасибо за вашу помощь :)

ответ

0

Я не знаю, если это быстрее, но это определенно короче. Дайте ему вращение?

text = "As the prices of U.S. homes started to falter, doubts arose throughout the global financial system. Banks became weaker, private credit markets stopped functioning, and by the end of the year it was clear that the world banks had sunk into a global recession." 

newDict = dict((k, text.count(k) + text.count(k.title())) for k in vocabulary_dict) 

В любом случае, вы должны задать этот вопрос на CodeReview