我想在另一個列表中的列表的片標點的索引處插入一個句子:的Python - 插入可變(多於一個號碼列表)
for x in range(len(final1)):
final1.insert(punc_num[x], punct[x])- WHY WONT THIS WORK?
任何幫助麻煩理解: - )
整個代碼:
所有的f = open("file.txt","r")
sentence= f.read()
print (sentence)
punctuations = ("'", "!", "(", ")", "-", "[", "]", "{", "}", ";", ":", '"', "<", ">", ".", "/", "?", "@", "#", "$", "%", "^", "&", "*", "_", "~", ",")
punc_num=[]
for x in sentence:
if x in punctuations:
punc_num.append(sentence.index(x))
print(punc_num)
punct=[]
for x in sentence:
if x in punctuations:
punct.append(x)
print(punct)
no_punct= ""
for y in sentence:
if y not in punctuations:
no_punct = no_punct + y
print (no_punct)
no_punct=no_punct.split()
final= (" ".join(sorted(set(no_punct), key=no_punct.index)))
print(final)
storing=[]
for x in no_punct:
storing.append (no_punct.index(x))
print (storing)
final1= (" ".join(sorted(set(no_punct), key=no_punct.index)))
print(final1)
for x in range(len(final1)):
final1.insert(punc_num[x], punct[x])
1'str'沒有'insert'方法。 2.如果你正在考慮'list.insert()'方法,它的參數應該是'index,object',而不是'object,object'。 – zondo
好吧,如果我將句子分成列表,我將如何插入索引(它在列表中) – Admin
其實,我的第二點是無效的;你*是*使用一個數字。爲了得到你想要的結果,你應該在'for'循環前加上'no_punct_list = list(no_punct)',然後在調用'insert()'時使用'no_punct_list'而不是'no_punct'。在for循環之後,你可以說'no_punct =「」.join(no_punct_list)'。如果這解決了你的問題,我會把它放在一個答案。 – zondo