복붙노트

[PYTHON] .txt 파일에서 가장 빈번한 단어를 찾는 Python 프로그램, 단어와 그 수를 인쇄해야 함

PYTHON

.txt 파일에서 가장 빈번한 단어를 찾는 Python 프로그램, 단어와 그 수를 인쇄해야 함

현재로서는 countChars 함수를 대체하는 함수가 있지만,

def countWords(lines):
  wordDict = {}
  for line in lines:
    wordList = lines.split()
    for word in wordList:
      if word in wordDict: wordDict[word] += 1
      else: wordDict[word] = 1
  return wordDict

하지만 프로그램을 실행하면이 가증함이 뱉어 내집니다 (이것은 단지 예일뿐입니다. 단어 옆에는 엄청난 수의 단어가 두 페이지 정도 있습니다)

before 1478
battle-field 1478
as 1478
any 1478
altogether 1478
all 1478
ago 1478
advanced. 1478
add 1478
above 1478

분명히 이것은 코드가 실행하기에 충분할만큼 건전하다는 것을 의미하지만, 내가 원하는 것을 얻을 수는 없습니다. 각 단어가 파일에 몇 번이나 인쇄되어야하는지 (Gettysburg 주소 인 gb.txt) 분명히 파일에있는 각 단어가 정확하게 1478 번 ..에 있지 않습니다.

나는 프로그래밍에 꽤 새로운데, 그래서 나는 다소 혼란 스럽다.

from __future__ import division

inputFileName = 'gb.txt'

def readfile(fname):
  f = open(fname, 'r')
  s = f.read()
  f.close()
 return s.lower()

def countChars(t):
  charDict = {}
  for char in t:
    if char in charDict: charDict[char] += 1
    else: charDict[char] = 1
  return charDict

def findMostCommon(charDict):
  mostFreq = ''
  mostFreqCount = 0
  for k in charDict:
    if charDict[k] > mostFreqCount:
      mostFreqCount = charDict[k]
      mostFreq = k
  return mostFreq

def printCounts(charDict):
  for k in charDict:
    #First, handle some chars that don't show up very well when they print
    if k == '\n': print '\\n', charDict[k]  #newline
    elif k == ' ': print 'space', charDict[k]
    elif k == '\t': print '\\t', charDict[k] #tab
    else: print k, charDict[k]  #Normal character - print it with its count

def printAlphabetically(charDict):
  keyList = charDict.keys()
  keyList.sort()
  for k in keyList:
    #First, handle some chars that don't show up very well when they print
    if k == '\n': print '\\n', charDict[k]  #newline
    elif k == ' ': print 'space', charDict[k]
    elif k == '\t': print '\\t', charDict[k] #tab
    else: print k, charDict[k]  #Normal character - print it with its count

def printByFreq(charDict):
  aList = []
  for k in charDict:
    aList.append([charDict[k], k])
  aList.sort()     #Sort into ascending order
  aList.reverse()  #Put in descending order
  for item in aList:
    #First, handle some chars that don't show up very well when they print
    if item[1] == '\n': print '\\n', item[0]  #newline
    elif item[1] == ' ': print 'space', item[0]
    elif item[1] == '\t': print '\\t', item[0] #tab
    else: print item[1], item[0]  #Normal character - print it with its count

def main():
  text = readfile(inputFileName)
  charCounts = countChars(text)
  mostCommon = findMostCommon(charCounts)
  #print mostCommon + ':', charCounts[mostCommon]
  #printCounts(charCounts)
  #printAlphabetically(charCounts)
  printByFreq(charCounts)

main()

해결법

  1. ==============================

    1.한 구절에서 여러 단어를 계산해야하는 경우 정규식을 사용하는 것이 좋습니다.

    한 구절에서 여러 단어를 계산해야하는 경우 정규식을 사용하는 것이 좋습니다.

    간단한 예부터 시작해 보겠습니다.

    import re
    
    my_string = "Wow! Is this true? Really!?!? This is crazy!"
    
    words = re.findall(r'\w+', my_string) #This finds words in the document
    

    결과:

    >>> words
    ['Wow', 'Is', 'this', 'true', 'Really', 'This', 'is', 'crazy']
    

    "Is"와 "is"는 서로 다른 두 단어입니다. 내 추측은 당신이 그들을 똑같이 세길 원한다는 것입니다, 그래서 우리는 단지 모든 단어를 대문자로 만들 수 있습니다.

    from collections import Counter
    
    cap_words = [word.upper() for word in words] #capitalizes all the words
    
    word_counts = Counter(cap_words) #counts the number each time a word appears
    

    결과:

    >>> word_counts
    Counter({'THIS': 2, 'IS': 2, 'CRAZY': 1, 'WOW': 1, 'TRUE': 1, 'REALLY': 1})
    

    여기까지 잘하니?

    이제 우리는 파일을 읽는 지금과 똑같은 작업을 수행해야합니다.

    import re
    from collections import Counter
    
    with open('your_file.txt') as f:
        passage = f.read()
    
    words = re.findall(r'\w+', passage)
    
    cap_words = [word.upper() for word in words]
    
    word_counts = Counter(cap_words)
    
  2. ==============================

    2.강력한 툴을 마음대로 사용할 수 있다면이 프로그램은 실제로 4 라이너입니다.

    강력한 툴을 마음대로 사용할 수 있다면이 프로그램은 실제로 4 라이너입니다.

    with open(yourfile) as f:
        text = f.read()
    
    words = re.compile(r"a-zA-Z'").findall(text)
    counts = collections.Counter(words)
    

    정규 표현식은 단어에 인접한 구두점과 관계없이 모든 단어를 찾습니다 (단어의 일부로 아포스트로피를 계산합니다).

    카운터는 사전과 거의 비슷하게 작동하지만 counts.most_common (10)과 같은 작업을 수행하고 개수를 추가 할 수 있습니다. help (Counter)

    부작용이없는 함수들만 재사용하기 쉽기 때문에 함수 printBy ...를 만들지 말 것을 제안합니다.

    def countsSortedAlphabetically(counter, **kw):
        return sorted(counter.items(), **kw)
    
    #def countsSortedNumerically(counter, **kw):
    #    return sorted(counter.items(), key=lambda x:x[1], **kw)
    #### use counter.most_common(n) instead
    
    # `from pprint import pprint as pp` is also useful
    def printByLine(tuples):
        print( '\n'.join(' '.join(map(str,t)) for t in tuples) )
    

    데모:

    >>> words = Counter(['test','is','a','test'])
    >>> printByLine( countsSortedAlphabetically(words, reverse=True) )
    test 2
    is 1
    a 1
    
  3. ==============================

    3.단어가 필요한 단어는 간단한 오타가 있습니다.

    단어가 필요한 단어는 간단한 오타가 있습니다.

    편집 : 소스를 편집 한 것 같습니다. 처음에는 올바르게 복사하려면 복사하여 붙여 넣기를 사용하십시오.

  4. ==============================

    4.가능한 해결책, ninjagecko의 것만 큼 우아하지는 않지만 여전히 :

    가능한 해결책, ninjagecko의 것만 큼 우아하지는 않지만 여전히 :

    from collections import defaultdict
    
    dicto = defaultdict(int)
    
    with open('yourfile.txt') as f:
        for line in f:
            s_line = line.rstrip().split(',') #assuming ',' is the delimiter
            for ele in s_line:
                dicto[ele] += 1
    
     #dicto contians words as keys, word counts as values
    
     for k,v in dicto.iteritems():
         print k,v
    
  5. ==============================

    5.

     words = ['red', 'green', 'black', 'pink', 'black', 'white', 'black', 
    'eyes','white', 'black', 'orange', 'pink', 'pink', 'red', 'red', 
    'white', 'orange', 'white', "black", 'pink', 'green', 'green', 'pink', 
    'green', 'pink','white', 'orange', "orange", 'red']
    
     from collections import Counter
     counts = Counter(words)
     top_four = counts.most_common(4)
     print(top_four)
    
  6. from https://stackoverflow.com/questions/10390989/python-program-that-finds-most-frequent-word-in-a-txt-file-must-print-word-and by cc-by-sa and MIT license