如何将单词列表和这些单词在句子中的位置保存为文件

时间:2016-10-08 21:04:31

标签: python

我的代码:(Python:v3.5.2)

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()

代码试图实现的目标:

上面的代码采用用户选择的句子,将该句子放入列表中,然后打印该列表中每个单词的位置,然后将用户的句子和用户句子的位置保存到一个简单的.txt文件。

问题:

如何让我的代码创建.txt文件,将用户的句子和用户句子中每个单词的位置保存到.txt文件中?

我对代码的当前问题是代码确实创建了一个.txt文件,但该文件中没有保存任何内容。

1 个答案:

答案 0 :(得分:1)

迭代包含句子单词的列表。对于每个单词,检查它是否存在于包含用于查找位置的单词的其他列表中。使用collections.defaultdict存储每个单词的index。以下是示例代码:

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]}

请参阅Python Print String To Text File,了解如何将内容写入文件。