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"
答案 0 :(得分:3)
.join()
方法只能加入字符串列表。您必须将int
列表中的position
转换为字符串:
file.write('\n'.join(str(p) for p in positions))
或
file.write('\n'.join(map(str, positions)))
答案 1 :(得分:2)
将positions
转换为字符串列表。
file.write('\n'.join(str(p) for p in positions))