Combine words from different .txt files to create a new big text



  • Hi, new to DrawBot.
    I am looking for a solutions for a master student at KASK.be.
    She want to combine 'words' from 3(or more) different .txt files.
    To create a new combined text.
    Every .txt file contains a big story in unformatted text.

    • So the text starts with the first word of text 1
    • …then the second word is the first word of text 2
    • …the third word is the first word of text 3
      This loop should go on until the 3 text files are finished.

    Anyone who could give us a suggestion to start with?
    Thanks
    Harold.



  • hello @pixelman,

    here’s a basic example showing how to make a new text by ‘rotating’ through the words in multiple input texts. it can handle texts with different amounts of words.

    txt1 = 'lorem ipsum dolor sit amet consectetur adipiscing elit'
    txt2 = 'donec dignissim tortor eget rhoncus hendrerit'
    txt3 = 'pellentesque at odio a dolor egestas molestie et non justo'
    
    # break each text into words
    words1 = txt1.split()
    words2 = txt2.split()
    words3 = txt3.split()
    
    # get the biggest amount of words
    wordCount = max(len(words1), len(words2), len(words3))
    
    # make an empty list to collect the combined words
    resultWords = []
    
    # count until the biggest amount of words
    for i in range(wordCount):
        # for each list of words
        for words in [words1, words2, words3]:
            # if the current index is smaller than the amount of words
            if i < len(words):
                # add the word at the current index to the list
                resultWords.append(words[i])
    
    # join combined words into a string
    result = ' '.join(resultWords)
    
    print(result)
    

    ‘real’ text usually includes punctuation, capital letters, etc. which makes the problem harder / more fun. you’ll need to think about how to handle those.

    succes!


    ps. and this is how you read a text file into a string:

    with open('example.txt', 'r', encoding='utf-8') as f:
        txt1 = f.read()
    


  • Hey gferreira, thankx we try to test it out tomorrow… many thanks!