2016-06-09 25 views
-2

Ich habe dieses Skript, es liest Datei (Datei besteht aus gesammelten Tweets), reinigt es, bekommt Häufigkeitsverteilung und erstellt Plot, aber jetzt kann ich nur mit einer Datei arbeiten, was ich brauche ist es, eine Funktion daraus zu erstellen, um mehr Dateien übergeben zu können. So kann ich Datenrahmen mit den Ergebnissen des freqdist aus mehreren Dateien erstellen plotten esWie schreibe ich eine Funktion in Python

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() 

Vielen Dank für jede Hilfe!

+3

Sie fragen also "wie mache ich eine Funktion"? [Hier gehts] (https://docs.python.org/3/tutorial/controlflow.html#defining-functions). – Kevin

+0

im Grunde ja, kann ich irgendwie nicht herausfinden, wie man es in Funktion –

+0

schreiben, so ist Ihr Problem, eine Funktion in Python zu schreiben, es ist nichts mit Datei lesen, Dataframe oder Plot zu tun. – Eular

Antwort

-1

Haben Sie das gemeint?

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

ich denke ja, danke! –

+0

Vergessen Sie nicht, es als richtig zu markieren, damit die Leute wissen, dass Sie Ihre Frage nicht mehr beantworten müssen :) – Brian

+0

Das führt zum Verlust der Datei, Sie sollten 'mit öffnen (Dateiname) als f: ...' – Daenyth

Verwandte Themen