簡體   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