Гематрия со списком слов - PullRequest
1 голос
/ 19 января 2012

Я новичок в программировании. Я пытаюсь сопоставить число (данное пользователем) с числовыми значениями слов в файле. Пример а = 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», а любые другие слова, соответствующие сложению их персонажей.

Ответы [ 2 ]

1 голос
/ 19 января 2012

Вот код с комментариями, которые описывают его подробно:

# 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.

0 голосов
/ 19 января 2012

Вы не читаете файл

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)
...