2017-01-16 80 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