2016-11-07 64 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。 :)

相关问题