输出文件

0 python python-3.x

这是我的代码

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()
Run Code Online (Sandbox Code Playgroud)

它生成文件但不保存任何内容.我究竟做错了什么?

Tig*_*kT3 6

你从未以任何方式写过任何文件.你可以通过几种方式做到这一点.由于您已经在使用看起来像Python 3的print功能,请尝试以下file参数:

print(UserSen, file=sentext)

...

print(position, file=postext)
Run Code Online (Sandbox Code Playgroud)

  • 从来不知道print有写入文件的选项.很高兴知道!+1 (3认同)