2015-02-04 13 views
0

여러 텍스트 파일이 있는데,이를 표현식과 단일 단어로 구성된 어휘 목록과 비교하고 싶습니다. 원하는 출력은 그 목록의 모든 요소를 ​​키로, 텍스트 파일의 각 빈도를 값으로 포함하는 사전이어야합니다.사전 정의 된 목록 요소의 출현 여부를 확인하려면 텍스트/문자열을 확인하십시오.

def word_frequency(fileobj, words): 
    """Build a Counter of specified words in fileobj""" 
    # initialise the counter to 0 for each word 
    ct = Counter(dict((w, 0) for w in words)) 
    file_words = (word for line in fileobj for word in line)    
    filtered_words = (word for word in file_words if word in words)  
    return Counter(filtered_words) 

def print_summary(filepath, ct): 
    words = sorted(ct.keys()) 
    counts = [str(ct[k]) for k in words] with open(filepath[:-4] + '_dict' + '.txt', mode = 'w') as outfile: 
    outfile.write('{0}\n{1}\n{2}\n\n'.format(filepath,', '.join(words),', '.join(counts))) 
    return outfile 

파이썬에서이 작업을 수행 할 수있는 방법이 있나요 : 내가 시도 내가 함께 두 개의 목록과 일치 할 필요는 어휘 목록,

list1 = ['accounting',..., 'yields', 'zero-bond'] 
list2 = ['accounting', 'actual cost', ..., 'zero-bond'] 
vocabulary_list = ['accounting', 'actual cost', ..., 'yields', 'zero-bond'] 

sample_text = "Accounting experts predict an increase in yields for zero-bond and yields for junk-bonds." 

desired_output = ['accounting':1, 'actual cost':0, ..., 'yields':2, 'zero-bond':1] 

를 구성하려면? 한 단어 (1 토큰)의 어휘 목록으로이를 관리하는 방법을 알아 냈지만 여러 단어의 경우에 대한 해결책을 찾지 못했습니다. 당신이 텍스트를 청소해야합니다 구두점으로 끝나는 단어를 고려할 경우

+0

한 단어로 된 해결책은 무엇입니까? 표현을 위해 어떤 방식으로 작동하지 않았습니까? # 각 단어에 대해 카운터를 0으로 초기화합니다. ct = 카운터 (dict (단어, w)에 대한 dict ((w, 0)) –

+0

def word_frequency (fileobj, words) : "" "fileobj에서 지정된 단어 카운터 생성")) 라인 단어에 대한 fileobj의 라인 = (워드 file_words) file_words의 단어에 대한 filtered_words = (단어 단어에서 단어) (filtered_words) –

+0

데프 print_summary (파일 경로, CT) 카운터를 반환 경우 : 단어 = 분류 ((파일 경로 [: - 4] + '_dict'+ '.txt', 모드 = 'w')를 outfile으로 사용하여 카운트 = [str (ct [k] : outfile.write ('{0} \ n {1} \ n {2}} \ n \ n'형식 (파일 경로, '. 조인 (단어),', '. 조인()) return outfile –

답변

0

또한 하나의 Vocab에서의 DICT에 'yields' 및 체인 'yields!'

from collections import Counter 
c = Counter() 
import re 

vocabulary_list = ['accounting', 'actual cost','yields', 'zero-bond'] 
d = {k: 0 for k in vocabulary_list} 
sample_text = "Accounting experts predict actual costs an increase in yields for zero-bond and yields for junk-bonds.".lower() 
splitted = set(sample_text.split()) 
c.update(splitted) # get count of all words 

for k in d: 
    spl = k.split() 
    ln = len(spl) 
    # if we have multiple words we cannot split 
    if ln > 1: 
     check = re.findall(r'\b{0}\b'.format(k),sample_text) 
     if check: 
      d[k] += len(check) 
    # else we are looking for a single word 
    elif k in splitted: 
     d[k] += c[k] 
print(d) 

모든 목록을 즉 :

from collections import Counter 
from itertools import chain 
import re 

c = Counter() 

l1,l2 = ['accounting', 'actual cost'], ['yields', 'zero-bond'] 
vocabulary_dict = {k:0 for k in chain(l1,l2)} 
print(vocabulary_dict) 
sample_text = "Accounting experts predict actual costs an increase in yields for zero-bond and yields for junk-bonds.".lower() 
splitted = sample_text.split() 
c.update(splitted) 

for k in vocabulary_dict: 
    spl = k.split() 
    ln = len(spl) 
    if ln > 1: 
     check = re.findall(r'\b{0}\b'.format(k),sample_text) 
     if check: 
      vocabulary_dict[k] += len(check) 
    elif k in sample_text.split(): 
     vocabulary_dict[k] += c[k] 
print(vocabulary_dict) 

문구 하나당 두 개의 dicts를 만들고 단어에 대한 두 개의 dicts를 만들고 각각을 통과 할 수 있습니다.

+0

좋은 솔루션 Padraic, 그러나 이와 같은 샘플에서는 작동하지 않습니다. sample_text = "회계 전문가. .. 실제 비용 ... 제로 - 채권 및 수익률에 대한 수익률의 증가를 예측 "-> ('실제 비용': 0, '회계': 1 ...) –

+0

@DominikScheld, 두 단어를 알아 차 렸습니다. –

+0

고마워요 Padraic :) 한가지 빠진 것, 스크립트 출력이 (... 'yields': 1) (... 'yields': 2)가되어야합니까? –