2016-04-21 55 views
0

我有一個txt文件與分割字符串,但只使用它的一些分析

Jordan: your pin is at 1257 
Harry: your pin is at 1390 

下面我如何使用拆分但那麼只有使用名稱和PIN在屏幕上打印出來並忽略其餘的呢?例如

For J in file: 
    A,b,c,d,d,f,g = J. Split 
    Print(a,g) 


Jordan 1257 
Harry 1390 
+0

這是單行嗎? 「喬丹:你的別針是1257哈利:你的別針是1390」 – jDo

回答

0

您可以使用名稱和銷指數:

file = ["Jordan: your pin is at 1257", "Harry: your pin is at 1390"] 

for line in file: 
    name = line.split()[0] 
    pin = line.split()[-1] 
    print(name + " " + pin) 

輸出:

Jordan: 1257 
Harry: 1390 

如果你想存儲的名稱和個人可以使用字典:

file = ["Jordan: your pin is at 1257", "Harry: your pin is at 1390"] 

myDictionary = {} 

for line in file: 
    name = line.split()[0][:-1] 
    pin = line.split()[-1] 
    myDictionary[name] = pin 

產量:

>>> for i,j in myDictionary.items(): 
    print(i + ":" + j) 


Jordan: 1257 
Harry: 1390 
0

我假設整個文本中的模式是相同的。 如果我正確理解你想要什麼,下面的代碼應該爲你做。它取代了你不帶空格想要的部分,只留下姓名和銷:

>>> input = "Jordan: your pin is at 1257 Harry: your pin is at 1390" 
>>> output = input.replace(": your pin is at ", " ") 
'Jordan 1257 Harry 1390' 

你只需要使用分裂如果你想創建一個列表,從得到的字符串:

>>> output.split() 
['Jordan', '1257', 'Harry', '1390']