繁体   English   中英

Python-插入变量(多个列表)

[英]Python - inserting a variable(list of more than one number)

我想在列表中的另一个列表的索引处插入标点符号:

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])

首先,当您使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM