Python 带多个参数的带列表项错误
我试图从文本文件中删除很多内容来重写它。 文本文件有几百个条目,每个条目由6行文本组成。 我让我的代码工作到这样一个程度:将所有行放入一个数组中,在每个项中只标识2个重要行,并删除空格,但任何进一步的剥离都会导致以下错误: “list”对象没有属性“strip” 这是我的代码:Python 带多个参数的带列表项错误,python,arrays,file,strip,multiple-arguments,Python,Arrays,File,Strip,Multiple Arguments,我试图从文本文件中删除很多内容来重写它。 文本文件有几百个条目,每个条目由6行文本组成。 我让我的代码工作到这样一个程度:将所有行放入一个数组中,在每个项中只标识2个重要行,并删除空格,但任何进一步的剥离都会导致以下错误: “list”对象没有属性“strip” 这是我的代码: x = 0 y = 0 names = [] colors = [] array = [] with open("AA_Ivory.txt", "r") as ins: for line in ins:
x = 0
y = 0
names = []
colors = []
array = []
with open("AA_Ivory.txt", "r") as ins:
for line in ins:
array.append(line)
def Function (currentElement, lineInSkinElement):
name = ""
color = ""
string = array[currentElement]
if lineInSkinElement == 1:
string = [string.strip()]
# string = [string.strip()]
# name = [str.strip("\n")]
# name = [str.strip(";")]
# name = [str.strip(" ")]
# name = [str.strip("=")]
names.append(name)
return name
# if lineInSkinElement == 2:
# color = [str.strip("\t")]
# color = [str.strip("\n")]
# color = [str.strip(";")]
# color = [str.strip(" ")]
# color = [str.strip("=")]
# colors.append(color)
# return color
print "I got called %s times" % currentElement
print lineInSkinElement
print currentElement
for val in array:
Function(x, y)
x = x +1
y = x % 6
#print names
#print colors
在名称的if语句中,删除第一个将导致错误。
我尝试将列表项转换为字符串,但在字符串周围得到了额外的[]
颜色的if语句可以忽略,我知道它是错误的,而试图修复它正是我当前问题的原因
但是我在绳子周围得到了额外的[]
您可以循环执行此操作以绕过列出的字符串。例如:
for lst, item in string:
item = item.strip("\n")
item = item.strip(";")
item = item.strip(" ")
item = item.strip("=")
name.append(item)
return name
这将使您找到列表中的字符串,您可以附加剥离的字符串
如果这不是您想要的,请发布一些您正在处理的数据以澄清。好的,我找到了解决方案。这是我的一个相当愚蠢的错误。由于strip函数周围的[]使结果成为列表或列表项,因此发生EERR错误。把它们取下来,就把它修好了。现在感觉放松了,有点愚蠢,但放松了。您也可以使用以下代码在一行中完成这项工作
item = item.strip("\n").strip("=").strip(";").strip()
最后一条将删除空白
这将仅删除\n元素。摆脱他们没有问题。问题是在那之后继续剥离。包含名称的行还包含不需要和不需要的元素,即。e、 =或但是,在它第一次剥离字符串后,它将其保存或作为列表处理。可以从同一字符串中删除更多元素。我想说的是,如果它将其保存为一个列表,则需要遍历该列表以剥离字符串。哦,我现在明白了。出于某种原因,它没有向我显示代码的中间部分。我尝试了同样的方法,除了使用变量名'str'而不是'item',它得到了postInteresting中声明的错误代码。你能在你的问题中发布一些你的数据吗?这样可能更容易解决:@Harri-永远不要使用内置类型/函数(如str或list等)已经使用的变量名,因为在这种情况下,您无法确定实际问题是什么。