我的代码:(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]}
有关如何将内容写入文件的信息,请参见Python打印字符串至文本文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句