带单词列表的数值占卜法

1 投票
2 回答
1128 浏览
提问于 2025-04-17 10:35

我刚开始学习编程,想要把用户输入的数字和文件中单词的数值进行匹配。比如说,a=1,b=2,c=3,A=1,B=2。如果用户输入“2”,那么输出的结果就是所有数值为2的单词。

userinput = raw_input("Please, enter the gematric value of the word: ")
inputfile = open('c:/school/dictionarytest.txt', 'r')
inputfile.lower()
output = []
for word in inputfile:
    userinput = ord(character) - 96
    output.append(character)
    print output
inputfile.close()

我对这些还不是很熟悉,语法也不太懂。有人能帮我一下吗?谢谢!

编辑1 - 比如用户输入数字7。如果列表中有单词“bad”(b=2,a=1,d=4),那么输出就应该是“bad”,还有其他所有字符加起来等于7的单词。

2 个回答

-1

你没有在读取这个文件

inputfile = open('c:/school/dictionarytest.txt', 'r')
file_input = inputfile.readlines().lower()
for character in file_input:
          if userinput == ord(character)-96:
                    output.append(character)
1

下面是带有详细注释的代码:

# ask user for an input until an integer is provided
prompt = "Please, enter the gematric value of the word: "
while True: # infinite loop
    try:        
        # ask user for an input; convert it to integer immediately
        userinput = int(raw_input(prompt))
    except ValueError: # `int()` can't parse user input as an integer
        print('the gematric value must be an integer. Try again')
    else:
        break # got an integer successfully; exit the loop

# use `with` statement to close the file automatically
# `'r'` is default; you don't need to specify it explicitly
with open(r'c:\school\dictionarytest.txt') as inputfile:
    #XXX inputfile.lower() # WRONG!!! file object doesn't have .lower() method

    # assuming `dictionarytest.txt` has one word per line
    for word in inputfile: # read the file line by line
        word = word.strip() # strip leading/trailing whitespace
        if gematric_value(word) == userinput:
           print(word) # print words that match user input

其中 gematric_value() 函数是:

def gematric_value(word):
    """Sum of numerical values of word's characters.

    a -> 1, b -> 2, c -> 3; A -> 1, B -> 2, etc
    """
    # word is a string; iterating over it produces individual "characters"
    # iterate over lowercased version of the word (due to A == a == 1)
    return sum(ord(c) - ord('a') + 1 for c in word.lower())

注意:在你的代码中不要使用上面的注释风格。这种风格仅适用于学习目的。你应该假设阅读你代码的人对Python是熟悉的。

撰写回答