여러 텍스트 파일이 있는데,이를 표현식과 단일 단어로 구성된 어휘 목록과 비교하고 싶습니다. 원하는 출력은 그 목록의 모든 요소를 키로, 텍스트 파일의 각 빈도를 값으로 포함하는 사전이어야합니다.사전 정의 된 목록 요소의 출현 여부를 확인하려면 텍스트/문자열을 확인하십시오.
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으로 초기화합니다. ct = 카운터 (dict (단어, w)에 대한 dict ((w, 0)) –
def word_frequency (fileobj, words) : "" "fileobj에서 지정된 단어 카운터 생성")) 라인 단어에 대한 fileobj의 라인 = (워드 file_words) file_words의 단어에 대한 filtered_words = (단어 단어에서 단어) (filtered_words) –
데프 print_summary (파일 경로, CT) 카운터를 반환 경우 : 단어 = 분류 ((파일 경로 [: - 4] + '_dict'+ '.txt', 모드 = 'w')를 outfile으로 사용하여 카운트 = [str (ct [k] : outfile.write ('{0} \ n {1} \ n {2}} \ n \ n'형식 (파일 경로, '. 조인 (단어),', '. 조인()) return outfile –