这是一个非常奇怪的错误,我根本无法理解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已经是一个列表了。好吧,我直接尝试做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()
问题出在嵌套的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))