2016-10-29 67 views
0
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上。列入文本文件的字符串?

例如,如果句子是'我喜歡英語,但我不喜歡數學'。 該計劃將輸出

['i','like','english,'but','do','not','maths'] 
[1,2,3,4,1,5,6,2,7] 

在文本文件,程序不輸出它 上面做了同樣的方式了一句。

有關如何使其在文本文件中做同樣的事情的任何建議?

+0

修復格式。 – khajvah

+0

那麼它在文本文件中輸出什麼? – UnholySheep

回答

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] 
+0

這個很有用。 – Zety