[英]Cannot remove last part of a list
我正在尝试编写程序。 该程序读取从文件中获取的字符串,将其分离,然后删除所有的'{'并将其替换为冒号(我现在正在尝试这样做)。 如果一行本身有一个“}”,则该行将被完全删除。 然后将新行放入另一个文件。
即如果我有:“ Def StackExchange {”,程序应返回“ Def StackExchange:”
我试图通过用空格将字符串分割并将其放入列表中来解决此问题。 之后,我遍历字符串并删除所有的“ {”,并在列表后附加“:”。
问题是,当我尝试删除'{'或添加':'时,出现ValueError,表明尽管字符在列表中,但{'不在列表中。
这是我到目前为止所拥有的:
readfile = open(filename + ".bpy","r")
writefile = open(filename + ".py","w")
line = readfile.readline()
string2 = []
while line != "":
string = line
string2 = []
string2.append(string.split())
if "{" in string2:
for x in string2:
try:
string2.remove("{")
string2.append(":")
string = string2.join(" ")
except:
pass
writefile.write(string)
string2 = [] #This resets string2 and makes it empty so that loop goes on
line = readfile.readline()
writefile.close()
readfile.close()
编辑:不使用.replace
我根本不会在单词列表中使用分割线来完成此任务。 我的建议:
with open(filename + '.bpy') as readfile, \
open(filename + '.py', 'w') as writefile:
for line in readfile:
if '{' in line:
line = line.replace('{', ':')
elif '}' in line:
continue
writefile.write(line)
使用@Aswin建议,您可以在该循环中直接替换大括号:
string2 = []
for character in string:
if character == '{':
string2.append(':')
else:
string2.append(character)
string = ''.join(string2)
问题在于实现了将字符串转换为单独单词的split方法。 如果其他字符和'{'之间没有空格,则不会分隔'{'。 最好分隔每个字符并对其进行处理,如以下代码片段所示。
string2 = list(string)
它将使奇迹。 其他,
string2 = []
for character in string:
string2.append(character)
它将撕裂每个字符并将其存储在数组中。 现在,您的条件将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.