0

嗨,我有一个关于 python 的问题,我是新手:

我有一个文本文件,其中包含按字母顺序排列的单词列表(大约 23000 个),就像一本小字典,每一行都是该文本文件中的一个单词

我必须制作一个程序要求用户输入九个字母,然后程序应该重新排列这些字母并在文本文件中找到与这组九个字母匹配的所有单词

我有点卡在这个程序的编码中,我需要一些帮助

这就是我所做的

Nian = raw_input ("Type in nine letters :")

filename = "dictionary.txt"
fil = open(filename, "r")

lines = fil.read()

tx4 = lines.strip()

a = Nian[0]    
b = Nian[1]      
c = Nian[2]       
d = Nian[3]       
e = Nian[4]    
f = Nian[5]      
g = Nian[6]    
h = Nian[7]     
i = Nian[8]

for w in lines[0:23005]:
       if a or b or c or d or e or f or g or h or i in lines:
       print w 
4

3 回答 3

2

So if it's an exact match of those 9 letters, we can be a little tricky here. Instead of creating all those permutations and checking each one, merely sort the words into alphabetical order using the python built-in sorted function (doc) and compare the result.

The "trick" here is realizing you're looking for an anagram for those 9 letters. For Example, 'terse' and 'reset' are anagrams of each other, but if you sort them they both turn into 'eerst'.

Even if you're not looking for exact matches you can still use this trick to make optimizations.

As for the rest of the program, if you look for some basic tutorials on reading a text file with python, I'm sure you'll be able to get through the rest of it. Good luck!

于 2011-09-20T19:42:37.870 回答
0

首先映入我脑海的是套装。

这可能不是理想的解决方案,但应该可以完成工作:

match_letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'}
for line in file:
    line = line.strip()
    line_letters = set(line)
    # test whether any letter from match_letters is in line_letters
    if line_letters & match_letters:
        print(line)

或者,如果我误解了并且您正在寻找包含所有九个字母的单词:

    if line_letters >= match_letters:
        print(line)

或者,如果您正在寻找包含这九个字母的单词:

    if line_letters <= match_letters:
        print(line)
于 2011-09-20T20:37:33.507 回答
0

以下是如何进行:

  1. 将文件读入 set() 对象,如果使用对象的方法,请不要忘记'\n'在行尾删除。readlines()file
  2. 使用http://docs.python.org/library/itertools.html#itertools.permutations遍历所有排列,并检查其中一个排列是否在您的集合中。也许您必须将元组映射到字符串,使用join方法str很有帮助。

你知道有9! = 362880排列吗?

于 2011-09-20T19:21:31.520 回答