2016-04-25 46 views
-1
sentence = raw_input("Enter a sentence: ") 
sentence = sentence.lower().split() 
uniquewords = [] 
for word in sentence: 
    if word not in uniquewords: 
     uniquewords.append(word) 

positions = [uniquewords.index(word) for word in sentence] 

recreated = " ".join([uniquewords[word] for word in positions]) 

positions = [x+1 for x in positions] 
print uniquewords 
print positions 
print recreated 

file = open('task2file1.txt', 'w') 
file.write('\n'.join(uniquewords)) 
file.close() 

file = open('task2file2.txt', 'w') 
file.write('\n'.join(positions)) 
file.close() 

這是我的代碼到目前爲止,一切工作除了保存位置爲文本文件,該錯誤消息我得到的是保存號碼到一個文件

"file.write('\n'.join(positions)) 
TypeError: sequence item 0: expected string, int found" 
+1

你嘗試粘貼錯誤信息到谷歌搜索? – TigerhawkT3

回答

2

轉換positions到字符串列表。

file.write('\n'.join(str(p) for p in positions)) 
3

.join()方法只能連接字符串列表。您必須在position列表轉換int s到字符串:

file.write('\n'.join(str(p) for p in positions)) 

file.write('\n'.join(map(str, positions))) 
+0

乾杯這有助於很多! – pythonprogrammer