将列表写入文本文件

时间:2016-04-19 13:12:12

标签: 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[i] for i in positions])

positions = [x+1 for x in positions]

print uniquewords
print positions
print recreated

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

python中的结果很好但是唯一的词不会进入文本文件。 我使用版本2.7.5和记事本作为文本文件。

2 个答案:

答案 0 :(得分:2)

join是一种字符串方法,您不应使用逗号,而应使用'\n'join之间的点。

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

答案 1 :(得分:0)

您需要结合您在问题中提到的两个部分。将第一部分放在最后,而不是打印报表。

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[i] for i in positions])

positions = [x+1 for x in positions]

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

正如您的示例所示,它目前尝试在文件包含任何内容之前将uniquewords写入文件。