2017-01-16 73 views
0

我有一個我正在開發的python字典制造商。我一直在拼湊,但我需要幫助。當我將它提交到一個文本文件或輸出時,它會在新文件之前重複單詞。例如,這可能是輸出一個時間: 一個 一個 一個 b 一個 ç如何刪除python輸出中的任何重複項

我需要的輸出爲 一個 b Ç

或(以幫助那些沒有得到它)的另一輸出的例子是: ABC CBA ABC CBA BCA

當它應該是: AAA AAB AAC ABA ABB ABC ACA ACB ACC 咩

等等。

任何人都可以幫助我嗎?這是我到目前爲止的代碼(將其保存到一個.txt名爲wordlist.txt文件)

import string, random 

minimum=input('Please enter the minimum length of any give word to be generated: ') 
maximum=input('Please enter the maximum length of any give word to be generated: ') 
wmaximum=input('Please enter the max number of words to be generate in the dictionary: ') 

alphabet =raw_input("What characters should we use to generate the random words?: ") 
string='' 
FILE = open("wordlist.txt","w") 
for count in xrange(0,wmaximum): 
    for x in random.sample(alphabet,random.randint(minimum,maximum)): 
     string+=x 
    FILE.write(string+'\n') 
    string='' 
print'' 
FILE.close() 
print 'DONE!' 
end=raw_input("Press Enter to exit") 
+0

你的問題不清楚。包括樣本輸入和樣本輸出。 – MYGz

+0

['itertools.product'](https://docs.python.org/2/library/itertools.html#itertools.product)應該可以幫助你。 –

回答

2

你只是想計算一個文件獨特的話嗎?爲什麼不:

with open("wordlist.txt","r") as wf: 
    content = wf.read() 
    words = [w.strip() for w in content.split(" ")] # or however you want to do this 
    # sets do not allow duplicates 
    # constructor will automatically strip duplicates from input 
    unique_words = set(words) 

print unique_words 
+0

這樣做時出現錯誤。 「wf.read」不能公開閱讀。 –

+0

你必須要更具體。什麼是錯誤?你正在運行的腳本是什麼?你能給幾行足夠的文件來測試嗎? – lollercoaster

+0

用__write__訪問打開文件!!! – volcano

0

你可以使用Python集收集來解決問題

下面你可以在下面一行new_alpha需要得到字母

new_alpha=''.join(set(alphabet)) 

之後添加行傳遞

for x in random.sample(new_alpha,random.randint(minimum,maximum)): 

以下是整個代碼: -

import string, random 

minimum=input('Please enter the minimum length of any give word to be generated: ') 
maximum=input('Please enter the maximum length of any give word to be generated: ') 
wmaximum=input('Please enter the max number of words to be generate in the dictionary: ') 

alphabet =raw_input("What characters should we use to generate the random words?: ") 
new_alpha=''.join(set(alphabet)) 
string='' 
FILE = open("wordlist.txt","w") 
for count in xrange(0,wmaximum): 
    for x in random.sample(new_alpha,random.randint(minimum,maximum)): 
     string+=x 
    FILE.write(string+'\n') 
    string='' 
print'' 
FILE.close() 
print 'DONE!' 
end=raw_input("Press Enter to exit") 
+0

那麼最終的代碼是什麼?我對python不太好...當我嘗試這個時,我總是收到錯誤。 –

+0

更新了上面的完整代碼 – PythonUser