2016-07-19 46 views
0

我試圖做一個函數,在給定用戶輸入的情況下,可以將輸入映射到文本文件中的字符串列表,並返回與文件中字符串對應的某個整數。基本上,我檢查用戶輸入是在文件中,並返回文件中匹配字符串的索引。我有一個工作功能,但它看起來很慢並且容易出錯。將用戶輸入映射到文本文件列表

def parseInput(input): 
    Gates = [] 
    try: 
     textfile = open("words.txt") 
     while nextLine: 
      nextLine = textfile.readline() 
      Gates[n] = nextLine #increment n somewhere 
    finally: 
     textfile.close() 
    while n <= len(Gates): 
     nextString = Gates[n] 
     if input in nextString: 
      #Exit loop 
    with open("wordsToInts.txt") as textfile: 
     #Same procedure as the try loop(why isn't that one a with loop?) 
     if(correct): 
      return number 

這似乎相當......不好。我似乎無法想到更好的方式來做到這一點。我完全控制words.txt和wordsToInts.txt(我應該結合這些嗎?),所以我可以根據自己的喜好來格式化它們。我正在尋找建議重新:功能本身,但如果文本文件的更改會有所幫助,我想知道。我的目標是減少錯誤原因,但我會稍後添加錯誤檢查。請提出一個更好的方法來編寫這個函數。如果用代碼編寫,請使用Python。然而,僞碼很好。

回答

0

我會說要合併文件。你可以有你的話,它們的對應值如下:

words.txt

string1|something here 
string2|something here 

然後你可以每行存儲爲一個條目字典和召回根據您輸入的值:

def parse_input(input): 
    word_dict = {} 
    with open('words.txt') as f: 
     for line in f.readlines(): 
      line_key, line_value = line.split('|', 1) 
      word_dict[line_key] = line_value.rstrip('\n') 
    try: 
     return word_dict[input] 
    except KeyError: 
     return None 
0

我試圖做的是,給定的來自用戶的輸入,可以映射輸入到一個文本文件中的字符串列表,並返回一些整數對應於100的功能依賴於文件中的字符串。從本質上講,我檢查用戶輸入的是文件在什麼和文件中返回匹配的字符串的索引

def get_line_number(input): 
    """Finds the number of the first line in which `input` occurs. 

    If input isn't found, returns -1. 
    """ 
    with open('words.txt') as f: 
     for i, line in enumerate(f): 
      if input in line: 
       return i 
    return -1 

此功能將滿足你的描述規範與附加假設字符串你關心是分開的。值得注意的東西:

  1. Python中的文件對象充當其內容行上的迭代器。如果您只需檢查每個單獨的行,則無需將行讀入列表中。

  2. enumerate函數採用一個迭代並返回發電機這產生像(index, element),其中element是在你的迭代和索引的元素是其迭代器內側的位置的元組。

    • 術語迭代器意味着任何對象都是可以在for循環中訪問的一系列事物。
    • 術語生成器意味着生成元素以通過「即時」迭代的對象。在這種情況下,這意味着您可以逐一訪問文件的每一行,而無需將整個文件加載到機器的內存中。
  3. 該函數是用標準的Pythonic風格編寫的,帶有文檔字符串,適當的變量名稱和描述性名稱。