2016-06-09 5 views
-2

이 스크립트는 파일 (파일은 수집 된 트윗으로 구성되어 있음)을 읽고, 정리하고, 빈도 분포를 얻고 플롯을 작성하지만, 이제는 하나의 파일로만 작업 할 수 있습니다. 더 많은 파일을 전달할 수있는 기능을 만드는 것입니다. 그래서 나는 더 많은 파일에서 freqdist 결과를 그릴 수 있습니다어떻게 파이썬에서 함수를 작성합니까?

f = open(.......) 
text = f.read() 
text = text.lower() 
for p in list(punctuation): 
    text = (text.replace(p, '')) 

allWords = nltk.tokenize.word_tokenize(text) 
allWordDist = nltk.FreqDist(w.lower() for w in allWords) 
stopwords = set(stopwords.words('english')) 

allWordExceptStopDist = nltk.FreqDist(w.lower() for w in allWords if w not in stopwords) 
mostCommon = allWordExceptStopDist.most_common(25) 

frame = pd.DataFrame(mostCommon, columns=['word', 'frequency']) 
frame.set_index('word', inplace=True) 
print(frame) 
histog = frame.plot(kind='barh') 
plt.show() 

정말 고마워요!

+3

"어떻게하면 기능을 만들 수 있습니까?" [여기 있습니다.] (https://docs.python.org/3/tutorial/controlflow.html#defining-functions). – Kevin

+0

기본적으로 네, 어떻게 든 알아낼 수 없지만 함수에 쓰는 방법을 알아낼 수 있습니다. –

+0

파이썬에서 함수를 작성하는 것이 문제이므로 파일 읽기, 데이터 프레임 또는 플롯과는 아무런 관련이 없습니다. – Eular

답변

-1

이게 무슨 뜻인가요?

def readStuff(filename) 
    with open(filename) as f: 
     text = f.read() 
    text = text.lower() 
    for p in list(punctuation): 
     text = (text.replace(p, '')) 

    allWords = nltk.tokenize.word_tokenize(text) 
    allWordDist = nltk.FreqDist(w.lower() for w in allWords) 
    stopwords = set(stopwords.words('english')) 

    allWordExceptStopDist = nltk.FreqDist(w.lower() for w in allWords if w not in stopwords) 
    mostCommon = allWordExceptStopDist.most_common(25) 

    frame = pd.DataFrame(mostCommon, columns=['word', 'frequency']) 
    frame.set_index('word', inplace=True) 
    print(frame) 
    histog = frame.plot(kind='barh') 
    plt.show() 
+0

나는 고맙다고 생각한다! –

+0

사람들이 당신의 질문에 다시 대답하지 않는 것을 알 수 있도록 올바른 것으로 표시하는 것을 잊지 마세요 :) – Brian

+0

이것은 파일 핸들을 누출합니다.'with open (filename) as f : ... '을 사용해야합니다. – Daenyth

관련 문제