如何删除python输出中的任何重复项

时间:2017-01-16 05:47:46

标签: python python-2.7

我正在制作一个python字典制作工具。我一直在拼凑它,但我需要帮助。当我将其提交到文本文件或输出时,它在新的之前有重复的单词。例如,这可能是一次输出: 一个 一个 一个 b 一个 ç

我需要输出 一个 b ç

或者(帮助那些没有得到它的人)另一个输出示例是: ABC CBA ABC CBA BCA

应该是: AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA

等等。

任何人都可以帮助我吗?这是我到目前为止的代码(它保存到名为wordlist.txt的.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")

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用python set collection来解决问题

下面的行,你可以在获得字母后添加

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

在下面的行中new_alpha需要传递

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