Search code examples
pythonpython-3.xpython-docx

Is there an easy way to add spaces to words in a List?


Alright, so here is what I am trying to do. I want easily convert the text from a text file into a word document. I currently have this...

from docx import Document

text_file = "pathToYourTextFile.txt"

#opens document to add text to
document = Document()

#adds the entire contents to a list that we will
#then use to add to the document we just created
fileContents = []
for line in open(text_file):
    row = line.split(' ')
    fileContents += list(row)

#adds all the text we just created to the document as a paragraph
paragraph = document.add_paragraph(fileContents)

#saves the document with all the under the name we give it
document.save('test.docx')
print("Document saved.")

Where the text from the text file is read then each word is added to a list. Then all the words are added to the Document but the problem is all the words run together and don't have any spaces.

Below is an example of what the text looks like...

GetreadytoentertheThrivetimeshowontalk.Radio1170broadcastinglivefromthecenteroftheuniverse.It'SbusinessschoolwithouttheBSfeaturingoptometristturnedentrepreneur.Dr.RobertzoellnerwithusSBA,entrepreneuroftheYearclayClark.Dowehavecominginfromoneofourlistenersthattheyasked?Howcanyoucontrolemployeesthatyoucannotfire?HowcanyoucontrolemployeesthatyoucannotfirewellSteve?Couldyouthrowoutsomeinstanceswherethatcouldbeathingwhereyoucouldn'tfiretosuchasuper?

So what I want to know is this the best way to do this? Is there a simpler way? Any help would be much appreciated. Thank you in advance!!!


Solution

  • Why did you split the line to some words? If you want to copy everything, you should go with the line(will copy the space and the new-line) instead of splitting it. So your code will be :

    from docx import Document
    
    text_file = "pathToYourTextFile.txt"
    
    #opens document to add text to
    document = Document()
    
    #adds the entire contents to a list that we will
    #then use to add to the document we just created
    fileContents = []
    for line in open(text_file):
        fileContents += line
    
    #adds all the text we just created to the document as a paragraph
    paragraph = document.add_paragraph(fileContents)
    
    #saves the document with all the under the name we give it
    document.save('test.docx')
    print("Document saved.")
    

    Nice commenting btw!

    Happy Coding!