sentence = input("Please enter a sentence:")
words = sentence.split()
position= [0]
myList = []
[myList.append(x) for x in words if x not in myList]
a =(" ".join(myList))
print (myList)
if words.count(i) <2:
position.append(max(position) +1)
else:
position.append(words.index(i) +1)
position.remove(0)
print (position)
words = str(words)
position = str(position)
file = open("recreated_positions","w")
file.write(a)
file.write(position)
file.close()
这段代码将每个单词的位置作为数字,并在python shell和textfile上打印句子。
例如,如果句子是&#39;我喜欢英语,但我不喜欢数学&#39; 。 该程序将输出
['i','like','english,'but','do','not','maths']
[1,2,3,4,1,5,6,2,7]
在文本文件中,程序不会以相同的方式输出句子 在上面。
有关如何使其在文本文件中执行相同操作的任何建议吗?
答案 0 :(得分:0)
首先,您需要从列表中删除重复项,然后使用index
获取元素的位置:
sentence = raw_input("Please enter a sentence:")
words = sentence.split()
myList = []
for x in words:
if x not in myList:
myList.append(x)
a = str(myList)
positions= [myList.index(word) + 1 for word in words]
print positions
file = open("recreated_positions","w")
file.write(a + '\n')
file.write(str(positions))
file.close()
输出:
[1, 2, 3, 4, 1, 5, 6, 2, 7]