2012-01-19 50 views
1

我是編程新手。我試圖將一個數字(由用戶給出)與文件中單詞的數字值進行匹配。示例a = 1。 B = 2,C = 3,A = 1,B = 2,因此,如果用戶輸入 「2」,那麼輸出將是列表中的匹配2.Gematria與單詞列表

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」,並且任何其他單詞匹配他們的角色的添加。

+0

文件對象(由'open()'函數返回)沒有'.lower()'方法。你可以用'word = word.lower()'來代替('word'是一個字符串,所以它有'.lower()'方法)。 – jfs

+0

*「匹配2的列表中的所有單詞」*是什麼意思?你能否提供一個例子:給出一個預期的輸出結果如何? – jfs

+0

例如用戶輸入數字7.如果單詞bad(b = 2,a = 1,d = 4)在列表中,則輸出將是「bad」,以及與其字符相加的任何其他單詞。 – Manifold

回答

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。

+0

完美,謝謝你答案。 – Manifold

-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) 
+0

這不起作用 - .lower()是一個字符串方法,而不是一個列表方法(這是readlines()返回的內容)。 – DSM

+0

-1:'for open in line('file.txt'): '讀取文件。 – jfs

+0

我現在有一個問題.lower(),如果我刪除,我有一個if userinput == ord(字符)-96: NameError:名稱'字符'未定義 – Manifold