您好我正在处理一个合并两个单独的.txt文件并输出个性化字母的函数。问题是,我可以在funciton模块中包含我的文本,它可以很好地工作。但是当我尝试在函数中打开它们并被函数使用时,我得到了这个
错误消息:
追踪(最近一次通话): 文件“/Users/nathandavis9752/CP104/davi0030_a10/src/q2_function.py”,第25行, data = cleanData(q2) 文件“/Users/nathandavis9752/CP104/davi0030_a10/src/q2_function.py”,第17行,在cleanData中 对query.split(' - ')中的项返回[item.strip()。split('\ n \ n')] AttributeError:'file'对象没有属性'split'
代码:
letter = open('letter.txt', 'r')
q2 = open('q2.txt', 'r')
def cleanData(query):
return [item.strip().split('\n\n') for item in query.split('--')]
def writeLetter(template, variables, replacements):
# replace ith variable with ith replacement variable
for i in range(len(variables)):
template = template.replace(variables[i], replacements[i])
return template
data = cleanData(q2)
print (data)
variables = ['[fname]', '[lname]', '[street]', '[city]']
letters = [writeLetter(letter, variables, person) for person in data]
for i in letters:
print (i)
Michael
dawn
lock hart ln
Dublin
--
kate
Nan
webster st
king city
--
raj
zakjg
late Road
Toronto
--
dave
porter
Rock Ave
nobleton
[fname] [lname]
[street]
[city]
Dear [fname]:
As a fellow citizen of [city], you and all your neighbours
on [street] are invited to a celebration this Saturday at
[city]'s Central Park. Bring beer and food!
答案 0 :(得分:0)
您正在尝试拆分文件缓冲区而不是字符串。
def cleanData(query):
return [item.strip().split('\n\n') for item in query.read().split('--')]