Python 将数字保存到文件中

Python 将数字保存到文件中,python,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 = [uniquewor

这是我到目前为止的代码,除了将位置保存到文本文件中,所有操作都正常,我收到的错误消息是

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"
.join()
方法只能连接字符串列表。必须将
位置
列表中的
int
s转换为字符串:

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


你试过把错误信息粘贴到谷歌搜索中吗?干杯,这帮了大忙!
file.write('\n'.join(str(p) for p in positions))
file.write('\n'.join(map(str, positions)))