所以我试图让我的程序从文本文件中打印出每个单词和标点符号的索引(当它出现时)。我已经完成了那部分。- 但问题是当我尝试使用这些索引位置重新创建带有标点符号的原始文本时。这是我的代码:
with open('newfiles.txt') as f:
s = f.read()
import re
#Splitting string into a list using regex and a capturing group:
matches = [x.strip() for x in re.split("([a-zA-Z]+)", s) if x not in ['',' ']]
print (matches)
d = {}
i = 1
list_with_positions = []
# the dictionary entries:
for match in matches:
if match not in d.keys():
d[match] = i
i+=1
list_with_positions.append(d[match])
print (list_with_positions)
file = open("newfiletwo.txt","w")
file.write (''.join(str(e) for e in list_with_positions))
file.close()
file = open("newfilethree.txt","w") …Run Code Online (Sandbox Code Playgroud)