2016-04-23 5 views
0

Gibt es eine Möglichkeit, eine lange Reihe von Wörtern in eine Textdatei in Python3 zu schreiben, so dass die Zeichenfolge über mehrere Zeilen geschrieben werden kann? Das habe ich bisher versucht.Wie schreibe ich eine lange Reihe von Wörtern in eine Textdatei?

Hier ist, was ich versuche, mir nicht sicher, zu tun

from nltk.tokenize import word_tokenize 

    my_list = word_tokenize(my_text) 
    my_list_string = ' '.join(my_list) 

    outfile = open("my_comp.txt", "a") 
    outfile.write(my_list_string) 
    outfile.close() 
+0

Ihr Titel nicht passen wirklich Ihre Beschreibung – karina

+0

Ich denke, das ist, was Sie für http://StackOverflow.com suchen/questions/10660435/pythonoway-to-create-a-long-multilinear string – karina

+0

Was meinen Sie mit "string kann über mehrere Zeilen geschrieben werden"? – EbraHim

Antwort

0

Nachdem ich Ihren Code bin es eine andere Möglichkeit ist dann eine neue Zeile jeder n-te Token

Aber wer weiß einzufügen, wie big n sollte ...

Sie sollten es wahrscheinlich nur dem Programm überlassen, das die Datei öffnet?

+0

das Programm öffnet einfach die Datei und schreibt sie in eine 'wirklich lange' Zeile. Selbst wenn die Zeichenfolge ungefähr 1000 Wörter enthält. –

+0

Ja. Ich verstehe. Und so behandelt dein Redakteur das. Wenn Sie es in einem Editor öffnen, der Zeilenumbruch unterstützt – karina

+0

Sonst würde ich vielleicht die Token durchschleifen und eine neue Zeile an jeden anhängen ... Ich weiß nicht ... 20. Token? – karina

1

eine Bibliothek gibt dafür ist in Python textwrap genannt:

Arbeiten wie unten

>>> import textwrap 
>>> strs = "Is there a way to write a long string of words to a text file in python3 so that the string can be written over several lines? This is what I have tried so far. Is there a way to write a long string of words to a text file in python3 so that the string can be written over several lines? This is what I have tried so far. " 
:

>>> print (textwrap.fill(strs, 20)) 
Is there a way to 
write a long string 
of words to a text 
file in python3 so 
that the string can 
be written over 
several lines? This 
is what I have tried 
so far. Is there a 
way to write a long 
string of words to a 
text file in python3 
so that the string 
can be written over 
several lines? This 
is what I have tried 
so far. 

Oder die Leitungslänge ändern:

>>> print (textwrap.fill(strs, 40)) 
Is there a way to write a long string of 
words to a text file in python3 so that 
the string can be written over several 
lines? This is what I have tried so far. 
Is there a way to write a long string of 
words to a text file in python3 so that 
the string can be written over several 
lines? This is what I have tried so far. 
>>> 
+0

Vielen Dank! das funktioniert perfekt! Gibt es einen ähnlichen Befehl für eine Zahlenfolge? Es scheint nicht zu funktionieren, auch nachdem die Zahlen in eine Zeichenfolge konvertiert wurden. –

Verwandte Themen