2016-11-07 103 views
1

我正在編寫一個程序,我想從一個文本文件中加載行到一個集合/列表中。從一個文本文件中的行到一個集合(Python)

我想要一個用戶輸入五個數字(用空格分隔)我的程序將檢查用戶用這些數字贏得多少次。開獎結果之間用逗號隔開,如果最低的3個數字匹配在某一天開獎結果我的程序將打印出所有匹配的結果是這樣的:

"Three of your numbers match with: 
01.27.1957 8,12,31,39,43,45 
01.27.1957 8,12,31,39,43,45" 

"Four of your numbers match with: 
01.27.1957 8,12,31,39,43,45 
01.27.1957 8,12,31,39,43,45 

"Five of your numbers match with: 
01.27.1957 8,12,31,39,43,45 
01.27.1957 8,12,31,39,43,45" 

我的文本文件看起來像這樣:

index date lottery_results 

1. 01.27.1957 8,12,31,39,43,45 
2. 02.03.1957 5,10,11,22,25,27 
3. 02.10.1957 18,19,20,26,45,49 
4. 02.17.1957 2,11,14,37,40,45 

和等等...

我被卡住了,我甚至不知道該如何開始。

def read_data(): 
    results = open("dl.txt", 'r') 

回答

0
import datetime 


file = open("dl.txt") 

#user input 
user_numbers = set(map(int, input('Enter numbers: ').split(','))) 

for line in file: 

    try: 
     line = line.split() 

     # converts the leading number (without the trailing '.') 
     num = int(line[0][:-1]) 
     # converts from string to datetime object using the format 
     date = datetime.strptime(line[1], '%d.%m.%Y') 
     # creates a set of the coma separated numbers 
     numbers = set(map(int, line[2].split(','))) 
     # matches between the user input to the numbers 
     matches = len(numbers & user_numbers) 

     print(matches, 'of your number matches with', date.strptime('%d.%m.%Y'), 'whose numbers were', ', '.join(map(str, numbers))) 

    except: 
     pass 
+0

不要使用明火'except's –

+0

它不workig ...輸入號碼後,這是我看到 [...] 7號線,在 user_numbers =集(地圖(INT ,輸入('輸入數字:').split(','))) ValueError:無效文字爲int()與基10:'2 3 10 39 24 49' – yayusha

+0

@yayusha我worte'split(',')' )',表示用戶數字應該用','分隔,而不是輸入中的空格。你可以改成'split()' – Uriel

0

好吧,我得到這個!這是很容易...

dl = open("dl.txt", "r") 
for line in dl: 
    line = line.split() 

產生這樣

['5861.', '03.11.2016', '7,8,17,22,26,38'] 

東西現在我可以通過這個列表導航。感謝Uriel和Jay。 :)

相關問題