我正在尝试运行这两个文件行,连接每个文件中的每个单词,但它读取了整个文件。
我的样本数据文件1:
work
play
Run Code Online (Sandbox Code Playgroud)
我的样本数据文件2:
ed
ing
Run Code Online (Sandbox Code Playgroud)
我希望将两个词连接在一起的结果:
worked
playing
Run Code Online (Sandbox Code Playgroud)
但我得到:
working
worked
playing
played
Run Code Online (Sandbox Code Playgroud)
我只想从每个文件逐行读取它:
我的代码:
file1 = []
file2 = []
with open('file1.txt','rU') as f:
for line in f:
#print line.rstrip()
file1.append(line.rstrip())
with open('file2.txt','rU') as f1: #cnn-lm input
for line1 in f1:
#print line1.rstrip()
file2.append(line1.rstrip())
resutl=[]
f=open('output.txt', "w")
for i in file1 :
for g in file2 :
temp=[]
temp.append(i)
temp.append(g)
w = (i + g)
temp.append(w)
result=i+','+g+','+str(w)
f.write(result)
f.write('\n')
print w
f.close()
Run Code Online (Sandbox Code Playgroud)
这是预料之中的,因为您正在执行双循环,也就是您的条款的乘积。
您必须使用简单的循环和来交错它们zip,如下所示:
with open('file1.txt','rU') as f1, open('file2.txt','rU') as f2:
for s,e in zip(f1,f2):
print("{}{}".format(s.rstrip(),e.rstrip()))
Run Code Online (Sandbox Code Playgroud)
我懂了
working
played
Run Code Online (Sandbox Code Playgroud)