我一直在尝试创建一个程序,它必须读入一个文件,找到唯一的单词和标点,将它们放到一个列表中,然后获取每个单词的位置并将它们存储在一个列表中。然后,使用列表,程序将重新创建文件。这是我的代码:import time
import re
words = open('words.txt')
sentence = words.read()
uniquewords = []
positions = []
punctuation = re.findall(r"[\w']+|[.,!?;]", sentence)
for word in punctuation:
if word not in uniquewords:
uniquewords.append(word)
print("This file contains the words and punctuation ", uniquewords)
positions = [uniquewords.index(word) for word in punctuation]
recreated = " ".join([uniquewords[i] for i in positions])
print("In a list the text file words.txt can be shown as:")
print(positions)
print("Recreating sentence...")
print(recreated)
上述程序执行其所需的操作,但它生成以下输出: