Python在文件中递归地串联字符串
我是一个完整的Python初学者,并且我知道你可以轻松地串接字符串,但是现在我有一个特定的需求,我觉得自己像个白痴,因为我不知道如何制作它工作。Python在文件中递归地串联字符串
我需要的是连接和重排列在file1.txt
一些单词和一些数字在file2.txt
例如,在file1.txt
有一个单词列表(每个字有一个换行符结尾):
apple
banana
pear
和file2.txt
有字的另一列表:
red
yellow
green
的IDE一个是从文件1的每个单词串联到每一个字的文件2,导致这样的事情:
applered
appleyellow
applegreen
bananared
bananayellow
bananagreen
pearred
pearyellow
peargreen
而这样的结果在另一个文本文件保存。我想我可以用我在python中的有限技能(来自codecademy和udemy)弄明白,但我不知道该怎么做。
代码
只需使用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号线我只输出列表
输出列表
['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)
非常感谢! 我不知道itertools! 我会修补它并学习一些,谢谢! – joe
这是低效的,可以通过输入文件上的两个简单循环来实现。 –
级联非常简单,您可以使用'+'并先做一点清理。
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')
让我知道,如果你想知道如何将其保存到一个新的文本文件,以及:)
你们都很棒! 非常感谢! – joe
您需要将问题分解成若干部分,如果需要,还可以针对每个问题提出一个单独的问题部分..你有什么第一个问题?请参阅[如何问](http://stackoverflow.com/help/how-to-ask) –
我说的是: 我不知道如何使所有单词从file1连接到所有单词文件2。 谢谢 – joe
由于您的文件很小,并且memoy不会成为问题,因此您可以只读取这两个文件的所有行。然后使用两个嵌套的'for'循环,或者一个列表理解来生成排列列表。或者你可以看看['itertools'](https://docs.python.org/2/library/itertools.html)。 –