我正在寻找以下代码的逻辑,以便根据条件将“Words”列表中的单词连接到不同的列表中: 每行的第一个单词进入Salutaion_List; 每行的第二个单词进入First-Name_list; 等...... 这样每次迭代的新单词必须连接成相应的列表(没有重写)!!!
我只用两行文本文件(2次迭代)尝试了它,当我在文本文件中添加额外的行时,第二行是由新行写的!! 谁能解决我的问题!!!
iPath= "C:\PythonInputs\Address.txt"
oPath="C:\PythonInputs\Address1.txt"
# declaration of all lists
with open(path) as f:
for i,line in enumerate(f):
if i == 0:
words=line.split('#')
#for word in words:
print words
word_count= len(words)
print ('number of words in the above line# %s\n') % word_count
salutation = words[0:1]
First_Name = words[1:2]
Middle_Name = words[2:3]
Last_Name = words[2:3]
Address = words[3:6]
City = words[-2:-1]
State = words[-1:]
elif i > 0:
words=line.split('#')
print words
word_count= len(words)
print ('number of words in the above line# %s\n') % word_count
salutation2 = words[0:1]
New_Sal = salutation + salutation2
print 'salutation: %s' % (",".join(New_Sal))
First_Name2 = words[1:2]
New_First_Name = First_Name + First_Name2
print 'First_Name: %s' % (",".join(New_First_Name))
Middle_Name2 = words[2:3]
New_Middle_Name = Middle_Name + Middle_Name2
print 'Middle_Name: %s' % (",".join(New_Middle_Name))
Last_Name2 = words[3:4]
New_Last_Name = Last_Name + Last_Name2
print 'Last_Name: %s' % (",".join(New_Last_Name))
Address2 = words[4:6]
New_Address = Address + Address2
print 'Address: %s' % (",".join(New_Address))
City2 = words[-2:-1]
New_City= City + City2
print 'City: %s' % (",".join(New_City))
State2 = words[-1:]
New_State = State+State2
print 'State: %s' % (",".join(New_State))
f.close()
**OUTPUT:**
['Mr', 'Name1', 'Name3', 'Address', 'Address1', 'Address2', 'Address3',
'City', 'State\n']
number of words in the above line# 9
['Mr', 'Name1', 'Name2', 'Name3', 'Address', 'Address1', 'City', 'State\n']
number of words in the above line# 8
salutation: Mr,Mr
First_Name: Name1,Name1
Middle_Name: ,Name2
Last_Name: Name3,Name3
Address: Address,Address1,Address2, Address,Address1
City: City,City
State: State
,State
答案 0 :(得分:0)
删除此行:
for i,line in enumerate(f):
这样做:
firstline = f.readline()
secondsline = f.readline()
并调整程序。