繁体   English   中英

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

[英]How to save a list of words and the positions of these words in the sentence as a file

我的代码:(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 文件,但该文件中没有保存任何内容。

迭代包含句子单词的列表。 对于每个单词,检查它是否存在于包含用于查找位置的单词的另一个列表中。 使用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]}

有关如何将内容写入 aa 文件,请参阅Python Print String To Text File

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM