2016-11-05 28 views
0

如何從文件中的一行中只取一個單詞並將其保存在某個字符串變量中? 例如,我的文件有一行「this,line,is,super」,我想只在可變字中保存第一個單詞(「this」)。我試圖逐字逐字閱讀「,」但是當我檢查它時,我收到了一個錯誤「類型'int'的參數不可迭代」。我怎樣才能做到這一點?只能從行中獲取一個字

line = file.readline() # reading "this, line, is, super" 
    if "," in len(line): # checking, if it contains ',' 
     for i in line: 
      if "," not in line[i]: # while character is not ',' -> this is where I get error 
       word += line[i] # add it to my string 

回答

1

一目瞭然,您正處於正確的軌道上,但是如果您始終考慮存儲哪種數據類型的位置,則可以解密一些錯誤。例如,你的條件「if」,「in len(line)」沒有意義,因爲它轉化爲「if」,「in 21」。其次,你迭代每一個字符,但你的價值不是你的想法。你想要在for循環中的那個點上的字符索引來檢查是否存在「,」,但是行[i]不像行[0],就像你想象的那樣,它實際上是行['t 「]。很容易假設我在你的字符串中總是一個整數或者索引,但是你想要的是一個整數值的範圍,等於該行的長度,遍歷並找到每個索引處的關聯字符。我已將您的代碼重新格式化以按照您的預期方式工作,並在考慮到這些說明的情況下返回word =「this」。我希望你能找到這樣的教學(有更短的方法和內置的方法來做到這一點,但理解指數在編程中至關重要)。假設線是字符串「this,line,is,super」:

if "," in line: # checking that the string, not the number 21, has a comma 
    for i in range(0, len(line)): # for each character in the range 0 -> 21 
     if line[i] != ",": # e.g. if line[0] does not equal comma 
      word += line[i] # add character to your string 
     else: 
      break # break out of loop when encounter first comma, thus storing only first word 
+0

謝謝你解釋我的錯誤。 :)並感謝你更多的調整你的解決方案,我的想法。 – Halep

2

你可以像這樣做,使用split():每個元素,你的情況,一個字

line = file.readline() 
if "," in line: 
    split_line = line.split(",") 
    first_word = split_line[0] 
    print(first_word) 

split()將創建一個列表。逗號將不會包含在內。

+0

謝謝。 :)你的解決方案非常整潔,可能我會在未來使用你的想法。如果我有能力選擇兩個最好的答案,我一定會選擇你的。但我需要選擇一個,在這種情況下,我比優雅的方法更有價值,更好的解釋。 – Halep