2013-08-14 2 views
1

누군가이 Python 코드를 더 잘 설명 할 수 있습니까? 나는 내가 할 수있는 언급,하지만 확실하지 않은 권리를 메신저 시도한이누군가이 Python 코드를 설명 할 수 있습니까?

from collections import Counter 
ignore = ['the','a','if','in','it','of','or', 'to','for','is','and','are'] 


file = raw_input("choose a file: ") 
filename = "" + file + ".txt" 


def main(): 
    with open(filename, 'r') as f: 
    p = f.read() # the variable p contains the contents of the file 

    words = p.split() #split the text file into individual words (strings) 

    wordCount = len(words) #count length of string, how many times does a specific string appear 
    print "The total number of words in the text file are:", wordCount 

    # Grab the top N words as input 

    counted_words = Counter(words) 

    for word in ignore: #check strings for any of the ignore words. 
     del counted_words[word] #delete words from 

    defined_words = int(raw_input("How many words do you want?")) #define amount of words to show 
    for word, count in counted_words.most_common(defined_words): #parse and store the most commmon words from the file 
      print word, count #print output 

main() 

을 worksw 방법에 대한 흥미있어, 파이썬에 대해 좀 더 배우려고 노력하고있어 나는?

+0

더 구체적으로 설명해야 할 부분은 무엇입니까? –

+2

이 코드는 실제로 작동하지 않습니다. 들여 쓰기가 깨졌습니다. Python은 실행하려고하면'IndentationError'를 발생시킵니다. – user2357112

답변

0

이 대부분 collections.Counter의 문서에 설명되어 있습니다 :

단어 수는 목록이 아닌 문자열의 길이는 논리에 관해서는
http://docs.python.org/2/library/collections.html#collections.Counter

... 그리고 카운트 무시한 단어를 삭제하기 전에 원래 입력에서 발견 된 총 단어 수입니다.

"상위 N을 잡아라"는 다음 문장이 아닌 프로그램 전체를 설명합니다.

counted_words는 핵심 단어로 사전에 필수적인 카운터 컬렉션이며 해당 단어 개수는 값으로 계산됩니다.

"for word in ignore :"루프는 나열된 일반 단어를 삭제합니다.

.most_common (number) 메서드는 카운트가 가장 큰 (숫자) 단어의 목록을 개수 기준으로 내림차순으로 반환합니다. 그것들은 원래의 입력에서 가장 흔한 (사소하지 않은) 단어입니다.

최종 for 루프가이를 인쇄합니다.

1

다음은 각 행에 대한 완전한 설명입니다.

from collections import Counter 
# the Counter object defines frequance testing 
ignore = ['the','a','if','in','it','of','or', 'to','for','is','and','are'] 
# this is just an array 


file = raw_input("choose a file: ") 
# prompts for input, incidentially not verified or tested in any way 
filename = "" + file + ".txt" 
# should be filename = file + ".txt" 


def main(): 
    with open(filename, 'r') as f: 
     # "with" opens and closes the file for working, and will do it even if the code errors, it's the right way to open files 
     p = f.read() # the variable p contains the contents of the file 

     words = p.split() #split the text file into individual words (strings) 

     wordCount = len(words) #count length of string, how many times does a specific string appear 
     # you comment is wrong. Count the number of words in the file 
     print "The total number of words in the text file are:", wordCount 

     # Grab the top N words as input (this is also wrong) 

     counted_words = Counter(words) 
     # this makes a frequancy counter 
     # is works sort of like {"word": #number-of-occuerences}, except trickier, but it can be accessed as such 
     # it's actually an objec that pretends to be a dictionary, look at the magic object methods for more info 

     for word in ignore: #check strings for any of the ignore words. 
      del counted_words[word] #deletes frequancy count entries 

     defined_words = int(raw_input("How many words do you want?")) #define amount of words to show 
     for word, count in counted_words.most_common(defined_words): 
      # counted_words.most_common(defined_words) is an array of tuples 
      # it has defined_words items 
      # each item is (word, count), it is sorted by count 
      print word, count #print output 

main()