我是python中的一个完全初学者,我了解到你可以轻松地连接字符串,但现在我有一个特定的需求,我觉得自己像个白痴,因为我不知道如何让它工作。
我需要的是连接和置换file1.txt
中的某些字词以及file2.txt
中的某些数字
例如,在file1.txt
中有一个单词列表(每个单词以换行符结尾):
apple
banana
pear
并且在file2.txt
中还有另一个单词列表:
red
yellow
green
这个想法是将file1中的每个单词连接到file2中的每个单词,结果是这样的:
applered
appleyellow
applegreen
bananared
bananayellow
bananagreen
pearred
pearyellow
peargreen
这样的结果将保存在另一个文本文件中。
我以为我可以通过我在python中的有限技能(来自codecademy和udemy)来解决这个问题,但我不知道该怎么做。
答案 0 :(得分:1)
只需使用itertools。
import itertools
file1Input = [line.strip() for line in open('file1.txt').xreadlines()];
file2Input = [line.strip() for line in open('file2.txt').xreadlines()];
output = [x[0] + x[1] for x in itertools.product(*[file1Input, file2Input])]
print(output)
说明:在第一行和第二行中,我只需打开file1.txt和file2.txt,读取所有行,删除它们,因为最后总会有换行并将它们保存到一个列表。在代码的第3行中,我对两个列表进行排列,并连接排列。在第3行,我只输出列表
['applered',
'appleyellow',
'applegreen',
'bananared',
'bananayellow',
'bananagreen',
'pearred',
'pearyellow',
'peargreen']
您可以轻松地将output
列表放入名为output.txt
thefile = open("output.txt","wb")
for item in output:
thefile.write("%s\n" % item)
或通过
显示for x in output:
print(x)
答案 1 :(得分:0)
连接很简单,你可以使用' +'并先做一点清洁。
with open('File1') as f:
#Convert all file contents to an array
f1=f.readlines()
with open('File2') as f:
f2=f.readlines()
#If you print the above two arrays you will see, each item ends with a \n
#The \n symbolizes the enter key
#You need to remove the <n (used strip for this) and then you can concatenate easily
#Saving to a text file should be simple after the steps below
for file_1_item in f1:
for file_2_item in f2:
print file_1_item.strip('\n')+file_2_item.strip('\n')
如果您想知道如何将其保存到新的文本文件,请告诉我们:)