Python 从文件中创建单词列表

标签 python list file

我正在尝试从一个文件中创建一个单词列表,该列表仅包含不包含任何重复字母的单词,例如“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/

相关文章:

python-2.7 - pandas:处理值为列表的列

C 逐字读取

java - for 循环的问题,接收和利用输入

python - Cassandra 中的行排序

python - Python 中的列标题重命名循环

java - 在字符串中存储和打印连续字符?

python - 从列表中随机抽取元素数据

php - 从php中的日志文件中删除存储在数组中的内容

不在路径上的包内的 Python 相对导入

python - 如何在 3D numpy 掩码数组上管理 2D 傅立叶变换 (FFT)?