2016-03-08 57 views
-1

我是一個完整的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)弄明白,但我不知道該怎麼做。

+0

您需要將問題分解成若干部分,如果需要,還可以針對每個問題提出一個單獨的問題部分..你有什麼第一個問題?請參閱[如何問](http://stackoverflow.com/help/how-to-ask) –

+0

我說的是: 我不知道如何使所有單詞從file1連接到所有單詞文件2。 謝謝 – joe

+0

由於您的文件很小,並且memoy不會成爲問題,因此您可以只讀取這兩個文件的所有行。然後使用兩個嵌套的'for'循環,或者一個列表理解來生成排列列表。或者你可以看看['itertools'](https://docs.python.org/2/library/itertools.html)。 –

回答

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號線我只輸出列表

輸出列表

['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) 
+0

非常感謝! 我不知道itertools! 我會修補它並學習一些,謝謝! – joe

+0

這是低效的,可以通過輸入文件上的兩個簡單循環來實現。 –

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') 

讓我知道,如果你想知道如何將其保存到一個新的文本文件,以及:)

+0

你們都很棒! 非常感謝! – joe