这是我的代码
sentext = open("urSentence.txt", "w")
UserSen = input("Enter your sentence of your choice, ")
print (UserSen)
sentext.close()
postext = open("ThePos.txt", "w")
listSplit = UserSen.split()
X = {} #this will make the words in a sentence assigned to a number
position=[]
for i,j in enumerate(listSplit): #"i" will count how many words there are in the sentence
if j in X:
position.append(X[j])
else:
X[j]=i
position.append(i)
print (position)
postext.close()
它生成文件但不保存任何内容。我做错了什么?
答案 0 :(得分:6)
你从未以任何方式写过任何文件。你可以通过几种方式做到这一点。由于您已经在使用Python 3的print
函数,请尝试使用file
参数:
print(UserSen, file=sentext)
...
print(position, file=postext)
答案 1 :(得分:1)
print
函数不会写入文件。你需要明确地写信给它。
sentext = open("urSentence.txt", "w")
UserSen = input("Enter your sentence of your choice, ")
sentext.write(UserSen)
sentext.close()
同样地:
postext = open("ThePos.txt", "w")
...
postext.write(str(position))
postext.close()