错误不可理解:var有时被视为列表,有时也被视为str

时间:2018-03-29 14:21:36

标签: python string list file attributes

这是一个非常奇怪的错误,我根本无法理解 Python 。 下面的说明详细说明了该功能应该做什么。

f和f2的创建和编写运作良好。我用一个例子来测试函数:histo_appels(['bob','jean','bob'],['21/03','22/03','28/03])

Python 给我一条错误消息:

  

line = line.split()// list对象没有属性'split'。

但在我的函数中,line应该是从f。

中提取的字符串

这意味着在我line = line.split()之前,行已经是一个列表。好吧,我直接尝试line.extend(line2),这次,Python会返回一条错误消息:

  

line.extend(line2)AttributeError:'str'对象没有属性'extend'

这意味着这一行是一个字符串,而它之前被认为是一个列表......

有什么想法吗?

def histo_appels(liste_contact, liste_date):
        liste = []
        s = set(liste_contact)
        l = list(s)
        # we identify the contact that try to call me 
        # set to remove doubles: ['bob','jean','bob'] becomes ['bob','jean']
        chaine = str(liste_contact)
        # count() can only be applied to a string

        f = open(r'c:\temp\historique_contact.txt','w',encoding='utf8')
        for i in range(len(s)):
            liste.append((l[i],chaine.count(l[i])))
            f.write(f"{l[i]} tried to call you {chaine.count(l[i])} time\n")
        f.close()
        # example : line 1 of f contains "bob tried to call you 2 time", 
        # and line 2 : "jean tried to call you 1 time"

        f2 = open(r'c:\temp\historique_date.txt','w',encoding='utf8')
        for i in s:
            liste1 = []
            for j in range(len(liste_contact)):
                if liste_contact[j] == i:
                    liste1.append(liste_date[j])
            f2.write(f"on the {liste1}\n")
            # example line 1 of f2 is "on the ['21/03','28/03']"
            # and line 2 of f2 is : "on the ['22/03']
        f2.close()

        # then we merge each line of f with f2 in a new file f3
        f = open(r'c:\temp\historique_contact.txt','r',encoding='utf8')
        f2 = open(r'c:\temp\historique_date.txt','r',encoding='utf8')
        f3 = open(r'c:\temp\historique_global.txt','w',encoding='utf8')
        for line in f:
            for line2 in f2:
                line = line.split()
                # on repasse line (=str) en liste
                line2 = line2.split()
                line.extend(line2)
                f3.write(" ".join(line))
        f3.close()
        f2.close()
        f.close()

1 个答案:

答案 0 :(得分:0)

问题出在嵌套for循环中:

for line in f:
    for line2 in f2:
        line = line.split()
        # on repasse line (=str) en liste
        line2 = line2.split()
        line.extend(line2)
        f3.write(" ".join(line))

当您进入第二个for循环时,您将继续拆分line,重新分配其值。我不明白你想做什么,但是在正确的for循环中split上调用line来解决这个具体问题:

for line in f:
    line = line.split()
    for line2 in f2:
        # on repasse line (=str) en liste
        line2 = line2.split()
        line.extend(line2)
        f3.write(" ".join(line))