我想在另一个列表中的索引列表中插入一个标点符号到句子中:
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])
答案 0 :(得分:0)
首先,当您使用final1.insert()
时,final1
是一个字符串,而不是一个列表。您可以通过执行以下操作来更新它:
final1_list = []
for x in range(len(punc_num)):
final1_list.insert(punc_num[x], punct[x])
final1 = "".join(final1_list)
其次,在定义punc_num
时,使用list.index()
方法。由于list.index()
将始终返回其参数的第一个次出现,因此任何给定的标点符号将始终具有相同的索引,无论它在字符串中出现的位置是多少。您可以将该循环更改为:
punc_num=[]
for x in sentence:
if x in punctuations:
index = 0
while index + sentence[index:].index(x) in punc_num:
index += sentence[index:].index(x) + 1
punc_num.append(index + sentence[index:].index(x))
您的整个程序应如下所示:
f = open("file.txt","r")
sentence = f.read()
print (sentence)
punctuations = ("'", "!", "(", ")", "-", "[", "]", "{", "}", ";", ":", '"', "<", ">", ".", "/", "?", "@", "#", "$", "%", "^", "&", "*", "_", "~", ",")
punc_num=[]
for x in sentence:
if x in punctuations:
index = 0
while index + sentence[index:].index(x) in punc_num:
index += sentence[index:].index(x) + 1
punc_num.append(index + sentence[index:].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)
final1_list = list(final1)
for x in range(len(punc_num)):
final1_list.insert(punc_num[x], punct[x])
final1 = "".join(final1_list)