将数字保存到文件中

时间:2016-04-25 10:27:33

标签: python

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"

2 个答案:

答案 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))