需要我的代码来计算每个单词的位置编号并存储要文件



我需要在python上开发一个程序,该程序在句子中识别单个单词并将其存储在列表中,但在句子中存储一个单词的位置号而不是实际单词。我已经开发了此代码,但是无法保存单词位置。

 sentence= input("Enter a sentence")
 keyword= input("Input a keyword from the sentence")
 words = sentence.split(' ')
 for i, word in enumerate(words):
    if keyword == word:
        print(i+1)
 file = open("newfile.txt","a")
 file.write(input("text to write in the file")+"/n")
 file.close()

有人得到任何建议,指针或帮助?

基于您的问题和代码段,我得出的结论是您的程序

  • 接受句子来自用户
  • 从用户获取关键字
  • 如果 word in 句子匹配 keyword ,请在文件中保存 Word Number >

因此,这是代码。

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
file=open("newfile.txt","a") #open the file in append mode
for i, word in enumerate(words):
  if keyword == word:
    file.write(str(i+1)+" ") #append the text. I've added space to distiguish digit.
file.close() #Close the file after loop.

最新更新