我正在尝试从一个文件中创建一个单词列表,该列表仅包含不包含任何重复字母的单词,例如“hello”,但会包含“helo”。
当我使用仅通过输入单词创建的列表时,我的代码词非常完美,但是当我尝试使用文件列表执行此操作时,它只会打印所有单词,即使它们包含重复的字母。
words = []
length = 5
file = open('dictionary.txt')
for word in file:
if len(word) == length+1:
words.insert(-1, word.rstrip('\n'))
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
x = 0
while x in range(0, len(alpha)):
i = 0
while i in range(0, len(words)):
if words[i].count(alpha[x]) > 1:
del(words[i])
i = i - 1
else:
i = i + 1
x = x + 1
print(words)
最佳答案
此代码段添加单词,并在插入之前删除重复的字母
words = []
length = 5
file = open('dictionary.txt')
for word in file:
clean_word = word.strip('\n')
if len(clean_word) == length + 1:
words.append(''.join(set(clean_word))
我们将字符串转换为集合,删除重复项,然后再次将集合连接到字符串:
>>> word = "helloool"
>>> set(word)
set(['h', 'e', 'l', 'o'])
>>> ''.join(set(word))
'helo'
我不是 100% 确定你想如何删除这样的重复项,所以我假设单词中的字母不能超过一次(因为你的问题指定了“重复字母”而不是“双字母”)。
关于Python 从文件中创建单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43970231/