How to save a list of words and the positions of these words in the sentence as a file
<p>My Code: (Python: v3.5.2)</p>

<pre><code>import time
import sys


def Word_Position_Finder():
    chosen_sentence = input("Make a simple sentence: ").upper()
    print("")
    print(chosen_sentence)
    print("")
    sentence_list = chosen_sentence.split()
    if len(chosen_sentence) == 0:
        print("Your sentence has no words.")
        time.sleep(1)
        Choose_To_Restart()        
    print(sentence_list)
    print("")
    time.sleep(1)
    users_choice = input("Press '1' to make a new sentence or press '2' keep current sentence: ")
    print("")
    if users_choice == "1":
        print("Restarting Program.")
        time.sleep(1)
        Restarting_Program()           
   elif users_choice == "2":
        print("")
        print("'" + chosen_sentence + "'" + " --- " + "Is your current  sentence.")
        print("")
        time.sleep(1)
        position = []
        for word in sentence_list:
            postions = position.append(sentence_list.index(word) + 1)
        print(position)
        with open("Positions.txt", "w") as text_file:
            print(chosen_sentence, position)
    else:
        print("That isn't a valid answer")
        Choose_To_Restart()
</code></pre>

<p>What the code is trying to achieve:</p>

<p>The code above takes a sentence of the users choice, makes that sentence into a list and then prints the position of each of those words in that list and then is meant to save the user's sentence and the positions of the user's sentence into a simple .txt file.</p>

<p>Question:</p>

<p>How do I make my code create .txt file that saves the user's sentence and the positions of each word in the user's sentence into that .txt file?</p>

<p>The current problem I am having with the code is that the code does create a .txt file but nothing is saved in that file.</p>

<p>Iterate over the list containing the words of sentence. For each word, check that whether it exists in the other list containing words for finding the positions. Use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> to store the <code>index</code> of each word. Below is the sample code:</p>

<pre><code>from collections import defaultdict

my_sentence = 'this is my sentence where this content is supposed to be checked'
sentence_words = my_sentence.split()
my_dict = defaultdict(list)
for i, item in enumerate(sentence_words):
    my_dict[item].append(i)

# content of 'my_dict':
# {'this': [0, 5], 'is': [1, 7], 'where': [4]}
</code></pre>

<p>Refer <a href="http://stackoverflow.com/questions/5214578/python-print-string-to-text-file">Python Print String To Text File</a> regarding how to write content to a a file.</p>

python