2017-05-21 2 views
1

안녕하세요. 저는 첫 번째 텍스트 파일을 읽어야하고 각 단어의 빈도를 계산하고 중복을 제거하고 파일에 단어와 개수가 포함 된 목록을 만듭니다.목록에있는 키워드의 빈도

내 두 번째 텍스트 파일에는 첫 번째 텍스트 파일에서 이러한 키워드의 빈도를 계산하고 가져 오기, dict 또는 zip을 사용하지 않고 결과를 반환하는 데 필요한 키워드가 들어 있습니다.

저는이 두 번째 부분에 대해 어떻게 가야할지 고집합니다. 파일을 열고 구두점을 지우지 않았지만 주파수를 찾는 방법이 없습니다. .find()의 아이디어로 놀았지만 아직 행운이 없습니다.

어떤 제안

이 순간에 내 코드가 아닌 첫 번째 텍스트 파일

def calculateFrequenciesTest(aString): 

    listKeywords= aString 
    listSize = len(listKeywords) 
    keywordCountList = [] 

    while listSize > 0: 
     targetWord = listKeywords [0] 
     count =0 
     for i in range(0,listSize): 
     if targetWord == listKeywords [i]: 
      count = count +1 

     wordAndCount = [] 
     wordAndCount.append(targetWord) 
     wordAndCount.append(count) 

     keywordCountList.append(wordAndCount) 

     for i in range (0,count): 
     listKeywords.remove(targetWord) 
     listSize = len(listKeywords) 

    sortedFrequencyList = readKeywords(keywordCountList) 

    return keywordCountList; 

편집 -에서 키워드 파일에 키워드의 주파수를 찾을 것입니다 주시면 감사하겠습니다 현재 아이디어로 주위 놀겠다는 거 첫 번째 파일을 다시 열지 만 이번에는 목록으로 바꾸지 않아도 되나요? 내 오류가 어떻게 든 내 목록 목록의 빈도를 세고에서 오는 것 같아요.

내가 예를 들어 단어의 목록을 복용하고 이러한 결과의 유형 내가

[[['the', 66], 1], [['of', 32], 1], [['and', 27], 1], [['a', 23], 1], [['i', 23], 1]] 
+0

당신이 할 수있는 것은 각각의 키워드를 거치고 그 키워드가 '빈도 목록'에 있으면 그 색인에서 바로 증가시키는 것입니다. –

+0

이것은 기본적으로 내가하고 싶었지만 몇 가지 다른 방법으로 시도했지만 작동하지 않았습니다. –

답변

1

당신은 뭔가를 시도 할 수 있습니다 얻고 있습니다.

word_list = ['hello', 'world', 'test', 'hello'] 
frequency_list = {} 
for word in word_list: 
    if word not in frequency_list: 
     frequency_list[word] = 1 
    else: 
     frequency_list[word] += 1 
print(frequency_list) 

RESULT: {'test': 1, 'world': 1, 'hello': 2} 

dicts에 제약 조건을 넣었으므로 두 목록을 사용하여 동일한 작업을 수행했습니다. 나는 그것이 얼마나 효율적인지는 모르겠지만 목적을 달성한다.

word_list = ['hello', 'world', 'test', 'hello'] 
frequency_list = [] 
frequency_word = [] 
for word in word_list: 
    if word not in frequency_word: 
     frequency_word.append(word) 
     frequency_list.append(1) 
    else: 
     ind = frequency_word.index(word) 
     frequency_list[ind] += 1 

print(frequency_word) 
print(frequency_list) 

RESULT : ['hello', 'world', 'test'] 
     [2, 1, 1] 

당신은 당신이 당신이에 대한 Counter를 사용해야합니다 @bereal에 동의

+1

['collections.Counter'] (https://docs.python.org/3.6/)에서 더 쉽게 할 수 있습니다. library/collections.html # collections.Counter) – bereal

+0

@PaulRooney 'frequency_list'는 dict이지만 다음과 같습니다. ( – bereal

0

을 원하는대로 재 요인을 좋아하거나하는 방법으로 변경할 수 있습니다. 나는 당신이 "수입, dict 또는 zip"을 원하지 않는다고 말한 것을 알고 있으므로이 대답을 무시해도 좋습니다. 그러나 파이썬의 가장 큰 장점 중 하나는 훌륭한 표준 라이브러리이며, list을 사용할 때마다 dict, collections.Counterre을 갖게됩니다.

코드에서 나는 C 또는 Java에서 사용했던 것과 동일한 스타일을 사용하고자한다는 인상을 얻고 있습니다. 나는 조금 더하려고 노력하는 것이 좋습니다 pythonic. 이 방법으로 작성된 코드 은 익숙하지 않은 것처럼 보일 수 있습니다., 시간이 오래 걸릴 수 있습니다. 그러나 더 많은 것을 배울 수 있습니다.

Claryfying 달성하고자하는 것은입니다. 파이썬을 배우고 있습니까? 이 문제를 해결하고 있습니까? 가져 오기, dict 또는 zip을 사용할 수없는 이유는 무엇입니까?

다음
#!/usr/bin/python 

import re   # String matching 
import collections # collections.Counter basically solves your problem 


def loadwords(s): 
    """Find the words in a long string. 

    Words are separated by whitespace. Typical signs are ignored. 

    """ 
    return (s 
      .replace(".", " ") 
      .replace(",", " ") 
      .replace("!", " ") 
      .replace("?", " ") 
      .lower()).split() 


def loadwords_re(s): 
    """Find the words in a long string. 

    Words are separated by whitespace. Only characters and ' are allowed in strings. 

    """ 
    return (re.sub(r"[^a-z']", " ", s.lower()) 
      .split()) 


# You may want to read this from a file instead 
sourcefile_words = loadwords_re("""this is a sentence. This is another sentence. 
Let's write many sentences here. 
Here comes another sentence. 
And another one. 
In English, we use plenty of "a" and "the". A whole lot, actually. 
""") 

# Sets are really fast for answering the question: "is this element in the set?" 
# You may want to read this from a file instead 
keywords = set(loadwords_re(""" 
of and a i the 
""")) 

# Count for every word in sourcefile_words, ignoring your keywords 
wordcount_all = collections.Counter(sourcefile_words) 

# Lookup word counts like this (Counter is a dictionary) 
count_this = wordcount_all["this"] # returns 2 
count_a = wordcount_all["a"] # returns 1 

# Only look for words in the keywords-set 
wordcount_keywords = collections.Counter(word 
             for word in sourcefile_words 
             if word in keywords) 

count_and = wordcount_keywords["and"] # Returns 2 
all_counted_keywords = wordcount_keywords.keys() # Returns ['a', 'and', 'the', 'of'] 
0

없이 수입이있는 솔루션입니다 :

그래서 여기 (파이썬 2 테스트) 그것은 가치가 무엇인지에 대한 기능 내장 이용하는 제안 (NO 타사)입니다. 작은 입력 배열에서 적은 수의 검색으로도 사용할 수있는 중첩 선형 검색을 사용하지만 큰 입력에서는 다루기가 쉽지 않고 느려집니다.

여전히 여기 입력은 상당히 큽니다.하지만 합리적인 시간에 처리합니다.나는 당신의 키워드 파일이 더 컸다는 것을 의심한다 (광산에는 단지 3 개의 단어가있다) 감속은 보여주기 시작할 것입니다.

여기서는 입력 파일을 가져 와서 줄을 반복하고 구두점을 제거한 다음 공백으로 분리하고 모든 단어를 단일 목록으로 병합합니다. 목록에는 중복 기호가 있으므로 목록을 제거하기 위해 목록을 정렬하여 중복 기호가 함께 오도록 한 다음 반복하여 반복하여 문자열과 개수가 포함 된 새 목록을 만듭니다. 동일한 단어가 목록에 나타나는 한 카운트를 증가시키고 새 단어가 표시되면 새 항목으로 이동하여이를 수행 할 수 있습니다.

이제 단어 빈도 목록이 생기며 필요한 키워드를 검색하고 개수를 검색 할 수 있습니다.

입력 텍스트 파일은 here이며 키워드 파일은 한 줄에 하나씩 파일에 몇 단어로 자갈로 표시 할 수 있습니다.

파이썬 3 코드, 그것은 당신이 이진 검색을 사용하는 findword을 수정할 수 있도록 경사 인 경우에 해당되는 경우 어떻게 파이썬 2

# use string.punctuation if you are somehow allowed 
# to import the string module. 
translator = str.maketrans('', '', '!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~') 

words = [] 
with open('hamlet.txt') as f: 
    for line in f: 
     if line: 
      line = line.translate(translator) 
      # py 2 alternative 
      #line = line.translate(None, string.punctuation) 
      words.extend(line.strip().split()) 

# sort the word list, so instances of the same word are 
# contiguous in the list and can be counted together 
words.sort() 

thisword = '' 
counts = [] 

# for each word in the list add to the count as long as the 
# word does not change 
for w in words: 
    if w != thisword: 
     counts.append([w, 1]) 
     thisword = w 
    else: 
     counts[-1][1] += 1 

for c in counts: 
    print('%s (%d)' % (c[0], c[1])) 

# function to prevent need to break out of nested loop 
def findword(clist, word): 
    for c in clist: 
     if c[0] == word: 
      return c[1] 
    return 0 

# open keywords file and search for each word in the 
# frequency list. 
with open('keywords.txt') as f2: 
    for line in f2: 
     if line: 
      word = line.strip() 
      thiscount = findword(counts, word) 
      print('keyword %s appear %d times in source' % (word, thiscount)) 

에 대한 수정을 나타냅니다,하지만 여전히 어디 근처 될 수 없습니다 a dict. collections.Counter은 제한이없는 경우에 적합한 솔루션입니다. 그것의 더 빠르고 적은 코드.