2014-11-21 78 views
0

我的代碼正在工作,但我有一個輕微的缺陷,我似乎無法修復它。我的代碼是:TextFile到一個字典

def Identifierare(): 
    File = open("FulaOrd.txt","r", encoding="utf-8") 
    for line in File: 
       if line.strip(): 
        Dict = {} 
        key, value = line.split(None, 1) 
        Dict[key] = value 
        print(Dict) 

Identifierare() 

我的結果是

{'debt': '3\n'} 
{'income': '2\n'} 
{'mortgage': '2\n'} 
{'sale': '2\n'} 

如何帶走反斜線N +在原來的文本文件,字寫得像這樣 債務3 收入2 抵押貸款2 銷售2

感謝一大堆!

+0

哦,忘了通知它是Python! – 2014-11-21 23:01:19

+0

'line.rstrip()。split()' – 2014-11-21 23:08:34

回答

2

而不是拆分line,拆分line.strip()首先將字符串返回和任何其他空白字符串。

+0

嗯我現在試過,但它給了我這個錯誤。 TypeError:strip()至多需要1個參數(給出2個) – 2014-11-21 23:06:33

+0

但是我現在設法解決了它。我嘗試使用.strip.split(無,1),它的工作。非常感謝您的建議! – 2014-11-21 23:07:47

0

一個簡單的答案是在分割線之前使用rstrip函數修剪字符串右側的空白字符(包括換行符)。

key, value = line.rstrip().split(None, 1) 
+0

哦天才!謝謝 :) – 2014-11-21 23:12:24