我需要在我试过的文本文件中保存唯一的词和位置
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和记事本作为文本文件。
答案 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
写入文件。