1

我是编程新手。我正在尝试将数字(由用户提供)与文件中单词的数值进行匹配。示例 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()

我对此有些陌生,语法并不那么熟悉。有人可以帮忙吗?谢谢

Edit1-示例用户输入数字 7。如果单词 bad (b=2,a=1,d=4) 在列表中,则输出将是“bad”,并且任何其他匹配其字符添加的单词.

4

2 回答 2

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。

于 2012-01-19T04:05:22.007 回答
-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)
于 2012-01-19T03:13:31.490 回答