留下你的话

2024-09-28 01:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序会生成一个字母组合列表,并检查它们是否是英语单词,但是程序漏掉了一些单词,我检查了字典文件,单词在那里但仍然没有在输出中,请告诉我为什么程序漏掉了很多结果,如homecornbarn等等。你知道吗

import itertools
#http://www.puzzlers.org/pub/wordlists/engwords.txt

with open('/Users/kyle/Documents/english words.txt') as word_file:
    english_words = set(word.strip().lower() for word in word_file if len(word.strip()) == 4)

for p1 in itertools.combinations('abcdefghijklmnopqrstuvwxyz', 4):
    word = ''.join(p1)
    if word in english_words:
        print '{} is {}'.format(word, word in english_words)

这是我正在使用的词典http://www.puzzlers.org/pub/wordlists/engwords.txt


Tags: inorg程序txthttpenglishwww单词
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:18

你要找的是productCartesian product),而不是combinations(这不会产生字母顺序不一致或重复的单词):

import string

for letters in itertools.product(string.ascii_lowercase, repeat=4):
    word = ''.join(letters)

    if word in english_words:
        print word

您还可以使用元组而不是字符串,这会加快速度:

import string
from itertools import product
#http://www.puzzlers.org/pub/wordlists/engwords.txt

with open('/Users/kyle/Documents/english words.txt', 'r') as word_file:
    english_words = set(tuple(word.strip().lower()) for word in word_file if len(word.strip()) == 4)

words = english_words.intersection(product(string.ascii_lowercase, repeat=4))

相关问题 更多 >

    热门问题