从文本文件到集合的行(Python)

时间:2016-11-07 22:28:53

标签: python list file text set

我正在编写程序,我想将文本文件中的行加载到set / list中。

我希望用户输入五个数字(用空格键分隔)我的程序将检查用户使用这些数字赢多少次。彩票结果以逗号分隔,如果最少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')

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果您的文件很小,请使用readlines。几百行被认为很小。

>>> open('/tmp/data', 'r').readlines()
['line1\n', 'line2\n', 'line3\n']

请参阅文档:https://docs.python.org/2.7/library/stdtypes.html?highlight=readlines#file.readlines

答案 2 :(得分: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。 :)