2016-03-23 6 views
1

Ich bin Anfänger in Python komplett. Ich habe viele Methoden aus stackoverflow Antworten auf diese Frage versucht, aber keiner von ihnen funktioniert in meinem Skript.
Ich habe dieses kleine Skript zu verwenden, aber ich kann nicht das große Ergebnis zu TXT-Datei, so dass ich die Daten analysieren kann. Wie leite ich die Druckausgabe in eine TXT-Datei auf meinem Computer um?Umleiten der Druckausgabe zu einer TXT-Datei in Python

from nltk.util import ngrams 
import collections 

with open("text.txt", "rU") as f: 
    sixgrams = ngrams(f.read().decode('utf8').split(), 2) 

result = collections.Counter(sixgrams) 
print result 
for item, count in sorted(result.iteritems()): 
    if count >= 2: 
     print " ".join(item).encode('utf8'), count 
+2

Wenn Sie Anfänger in Python sind und vor allem, da es scheint, dass Sie NLP tun Ich würde dir empfehlen, direkt zu Python 3 zu wechseln! –

Antwort

4

print statement in Python 2.x Unterstützung Umleitung (>> fileobj):

... 
with open('output.txt', 'w') as f: 
    print >>f, result 
    for item, count in sorted(result.iteritems()): 
     if count >= 2: 
      print >>f, " ".join(item).encode('utf8'), count 

In Python 3.x akzeptiert print function optionale Schlüsselwort Parameter file:

print("....", file=f) 

Wenn Sie in Python 2.6+ from __future__ import print_function machen, ist der obige Ansatz auch in Python 2.x möglich.

5

tun Sie es einfach auf der Kommandozeile: python script.py > text.txt

1

ein BufferedWriter verwenden Sie können es tun, wie diese

os = io.BufferedWriter(io.FileIO(pathOut, "wb")) 
os.write(result+"\n") 
for item, count in sorted(result.iteritems()): 
    if count >= 2: 
    os.write(" ".join(item).encode('utf8')+ str(count)+"\n") 

outs.flush() 
outs.close() 
0

Wie Antti erwähnt, sollten Sie python3 und lassen Sie alle diese lästige python2 Junk hinter Sie bevorzugen. Das folgende Skript funktioniert mit python2 und python3.

Zum Lesen/Schreiben von Dateien verwenden Sie open Funktion aus dem io Modul, das ist Python2/Python3 kompatibel. Verwenden Sie immer die with Anweisung, um eine Ressource wie eine Datei zu öffnen. Die with wird verwendet, um die Ausführung eines Blocks innerhalb einer Python Context Manager zu wickeln. Dateideskriptoren haben context mananger implementend und werden beim Verlassen des Blocks with automatisch geschlossen.

nicht auf Python ab, wenn Sie einen Text-Datei lesen möchten, können Sie die Codierung dieser Datei es richtig zu lesen wissen sollten (wenn Sie nicht sicher sind, utf-8 zuerst versuchen). Außerdem ist die korrekte UTF-8-Signatur utf-8 und der Modus U ist .

#!/usr/bin/env python 
# -*- coding: utf-8; mode: python -*- 

from nltk.util import ngrams 
import collections 
import io, sys 

def main(inFile, outFile): 

    with io.open(inFile, encoding="utf-8") as i: 
     sixgrams = ngrams(i.read().split(), 2) 

    result = collections.Counter(sixgrams) 
    templ = "%-10s %s\n" 

    with io.open(outFile, "w", encoding="utf-8") as o: 

     o.write(templ % (u"count", u"words")) 
     o.write(templ % (u"-" * 10, u"-" * 30)) 

     # Sorting might be expensive. Before sort, filter items you don't want 
     # to handle, btw. place *count* in front of the tuple. 

     filtered = [ (c, w) for w, c in result.items() if c > 1] 
     filtered.sort(reverse=True) 

     for count, item in filtered: 
      o.write(templ % (count, " ".join(item))) 

if __name__ == '__main__': 
    sys.exit(main("text.txt", "out_text.txt")) 

Mit der Eingabe text.txt Datei:

At eight o'clock on Thursday morning and Arthur didn't feel very good 
he missed 100 € on Thursday morning. The Euro symbol of 100 € is here 
to test the encoding of non ASCII characters, because encoding errors 
do occur only on Thursday morning. 

ich folgendes output_text erhalten:

count  words 
---------- ------------------------------ 
3   on Thursday 
2   Thursday morning. 
2   100 € 
Verwandte Themen