我从学校分配的全部任务是:
开发一个程序,识别句子中的单个单词,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。
例如,句子
select t.*, e.*
from employeetimesheets t
left join employeetimesheets t2 on t.employee_id = t2.employee_id
and t.empsheet_id < t2.empsheet_id
join employees e on t.employee_id = e.employee_id
where t.timesheet_status = 'Pending Approval'
and t2.employee_id is null;
包含单词ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY
可以使用序列从此列表中的这些单词的位置重新创建句子
ASK, NOT, WHAT, YOUR, COUNTRY, CAN, DO, FOR, YOU
将单词列表和这些单词在句子中的位置保存为单独的文件或单个文件。
分析该系统的要求,并设计,开发,测试和评估程序:
识别句子中的单个单词并将其存储在列表中 为该列表中的单词创建一个位置列表 将这些列表保存为单个文件或单独的文件。
这是我目前的代码:
1,2,3,4,5,6,7,8,9,1,3,9,6,7,8,4,5
这不起作用。我得到的错误是:
sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positionofword=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
sentencetext=sentence.isalpha or sentence.isspace()
while sentencetext==False: #if letters have not been entered
print("Only letters are allowed") #error message
sentence=input("Please enter a sentence").upper() #asks the question again
sentencetext=sentence.isalpha #checks if letters have been entered this time
elif question=="N":
print("The program will now close")
else:
print("please enter a letter")
sentence_word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
print(sentence)
sentence_words = sentence.split(' ')
for (i, check) in enumerate(sentence_words): #orders the words
if (check == word):
positionofwords=print(i+1)
break
else:
print("This didn't work")
words.write(str(sentence_words) + " ")
position.write(str(positionofwords) + " ")
words.close()
position.close()
我想知道的是NameError: name 'positionofwords' is not defined
在这种情况下不起作用以及我会做什么。
答案 0 :(得分:0)
>>> s = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'
>>> words = s.split()
>>> for w in words:
print(words.index(w) + 1)
输出:
1
2
3
4
五
6
7
8
9
1
3
9
6
7
8
4
5