我在互联网上找到了以下代码,它意味着输出列表中单词的位置:
mylist
但它不起作用,这是代码:
mylist="example string with spaces"
sentencelist=[]
for z in mylist.split(" "):
sentencelist.append(z)
wordlist=[]
for z in range(len(sentencelist)):
if sentencelist[z] not in wordlist:
wordlist.append(sentencelist[z])
wordpositions=[]
for i in range (len(sentencelist)):
for o in range(len(wordlist)):
if sentencelist[i]==wordlist[o]:
wordpositions.append(o+1)
wordlist=str(wordlist)
wordpositions=str(wordpositions)
inputFile=open("sentence.txt","w")
inputFile.write(wordlist)
inputFile.write("\n")
inputFile.write(wordpositions)
inputFile.close()
没有出现错误消息,但它也无法正常工作。有人可以expalin
答案 0 :(得分:1)
对我来说,脚本会成功写入内容为sentence.txt
和wordlist
的文件wordpositions
。
如果您想将这些打印到控制台,请添加:
print(wordlist)
print(wordpositions)