【问题标题】:How do i sort the datetime from oldest to newest, excluding all the duplicate words in python from textfile如何从最旧到最新对日期时间进行排序,从文本文件中排除 python 中的所有重复单词
【发布时间】:2019-12-28 12:47:30
【问题描述】:

这是我的文本文件:

['hello', 'sffr', '18/08/2019 21:36:43', '1']

['bye', 'asadf', '19/08/2019 18:23:15', '1']

['bye', 'asadf', '19/08/2019 19:53:15', '2']

['bye', 'sdfsd', '23/08/2019 15:40:24', '3']

['flower', 'hellooooo', '23/08/2019 15:41:37', '1']

['hello', 'hlekfhdfld', '23/08/2019 15:41:45', '2']

['flower', 'dfgdfg', '23/08/2019 15:41:59', '2']

['pot', 'sdf', '23/08/2019 15:45:14', '1']

我想按日期时间从最旧到最新对数据进行排序,并排除所有重复的单词。对于每个单词,我想采用最新的时间。

以下是我做的代码,我只设法逐字从文件中取出日期时间,但我无法获得最新的时间并将整个数据从最旧到最新排序。

import csv

word = input('\nAdd a word: ')

sorted_dates = []
with open('history.txt', 'r') as readFile:
    csvreader = csv.reader(readFile, delimiter=',', quotechar="'")

    for i, line in enumerate(csvreader, 1):
        if not line:
            continue
        if word in line[0]:
            sorted_dates = line[2]
            print(sorted_dates)

这是我的时间戳代码:

timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")

预期的输出是:

['bye', 'sdfsd', '23/08/2019 15:40:24', '3']

['hello', 'hlekfhdfld', '23/08/2019 15:41:45', '2']

['flower', 'dfgdfg', '23/08/2019 15:41:59', '2']

['pot', 'sdf', '23/08/2019 15:45:14', '1']

【问题讨论】:

    标签: python-3.x list datetime timestamp text-files


    【解决方案1】:

    看起来你需要。

    data = [['hello', 'sffr', '18/08/2019 21:36:43', '1'],
    ['bye', 'asadf', '19/08/2019 18:23:15', '1'],
    ['bye', 'asadf', '19/08/2019 19:53:15', '2'],
    ['bye', 'sdfsd', '23/08/2019 15:40:24', '3'],
    ['flower', 'hellooooo', '23/08/2019 15:41:37', '1'],
    ['hello', 'hlekfhdfld', '23/08/2019 15:41:45', '2'],
    ['flower', 'dfgdfg', '23/08/2019 15:41:59', '2'],
    ['pot', 'sdf', '23/08/2019 15:45:14', '1']]
    
    seen = set()
    result = []
    for i in sorted(data, key=lambda x: x[2], reverse=True):
        if i[0] not in seen:
            result.append(i)
            seen.add(i[0])
    
    print(sorted(result, key=lambda x: x[2]))
    

    输出:

    [['bye', 'sdfsd', '23/08/2019 15:40:24', '3'],
     ['hello', 'hlekfhdfld', '23/08/2019 15:41:45', '2'],
     ['flower', 'dfgdfg', '23/08/2019 15:41:59', '2'],
     ['pot', 'sdf', '23/08/2019 15:45:14', '1']]
    

    读取数据

    import ast
    data = []
    with open('history.txt', 'r') as readFile:
        for line in readFile:
            line = line.strip()
            if line:
                data.append(ast.literal_eval(line.strip()))
    

    【讨论】:

    • 是否可以从我提供的文本文件中检索数据,而不是在 python 本身上输入数据?我正在使用这行代码来检索: ``` with open('history.txt', 'r') as readFile: csvreader = csv.reader(readFile, delimiter=',', quotechar="'") for i,枚举中的行(csvreader,1):如果不是行:继续```
    • 嗨,请帮帮我@rakesh
    • 更新了 sn-p
    猜你喜欢
    • 2021-04-30
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多