此代码允许用户输入一个句子。然后将单词转换为位置。e、 g bob是伟大的bob变成0,1,2,0,然后将这些位置转换回原始数组,因此0,1,2,0变成bob是伟大的bob。然而,每当我用标点符号在一个句子上重复一个单词时,像bob就是伟大的bob!它打印位置0,1,2,0,4,语法错误显示“列表索引超出范围”。我不知道为什么这段代码在没有重复单词的情况下可以很好地使用标点符号,因此需要帮助来解决这个问题
import re
sentence=('bob is great bob!')
punctuation=(re.findall(r"[\w'\"]+|[.,!?;:_-]", sentence))
print(punctuation)
positions = [punctuation.index(x) for x in punctuation]
print(positions)
test1=(",".join(str(i) for i in positions))
words=" ".join(sorted(set(punctuation), key=punctuation.index))
print(words)
with open('1.txt', 'w') as f:#this creates the name of the file called task 2 which will contain my data ad allows the computer to locate the fle and add in the data. The 'w' makes the file writable so i can add in my data, without it displaying an error, using f as a variable.
f.write(str(words))
with open('2.txt', 'w') as f:
f.write(str(test1))
f.close()
openfile=('1.txt')
openfile = open(openfile, "r")
print ( openfile.read())
openfile=('2.txt')
openfile = open(openfile, "r")
print ( openfile.read())
openfile = open('1.txt', "r")
test=openfile.read()
#print(test)
blankarray=[]
for i in test.split(" "):
blankarray.append(i)
#print(blankarray)
openfile.close
openfile = open('2.txt', "r")
test=openfile.read()
#print(test)
blankarray2=[]
for i in test.split(","):
blankarray2.append(int(i))
#print(blankarray2)
openfile.close
blankstring=""
for i in range(len(blankarray2)):
#print(i)
blankstring=blankstring+blankarray[blankarray2[i]] + " "
print(blankstring)
目前没有回答
相关问题 更多 >
编程相关推荐