如何逐行读取文件并在python中打印只有特定字符串的行?

2024-09-30 18:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含这些行的文本文件

wbwubddwo 7::a number1 234 **
/// 45daa;: number2 12

time 3:44

我正在尝试打印,例如,如果程序找到字符串number1,它将打印234

我开始与下面的简单脚本,但它没有打印我想要的。你知道吗

with open("test.txt", "rb") as f:
    lines = f.read()
    word = ["number1", "number2", "time"]
    if any(item in lines for item in word):
        val1 = lines.split("number1 ", 1)[1]
        print val1

这将返回以下结果

234 **
/// 45daa;: number2 12

time 3:44

然后我试着把f.read()改成f.readlines(),但这次没有打印出任何内容。你知道吗

有人知道其他方法吗?最后,我想得到每一行的值,例如234123:44,并将其存储在数据库中。你知道吗

谢谢你的帮助。我真的很感激。你知道吗


Tags: 字符串in程序脚本readtimewithitem
3条回答

解释如下:

with open("test.txt", "r") as f:
    lines = f.readlines()
    stripped_lines = [line.strip() for line in lines]

words = ["number1", "number2", "time"]
for a_line in stripped_lines:
    for word in words:
        if word in a_line:
            number = a_line.split()[1]
            print(number)

1)首先“rb”给出bytes对象,即返回b'number1 234'之类的内容,使用“r”获取string对象。你知道吗

2)你读到的行是这样的,它将存储在一个列表中。你知道吗

['number1 234\r\n', 'number2 12\r\n', '\r\n', 'time 3:44']

注意\r\n它们指定您有一个换行符。要删除,请使用strip()。你知道吗

3)从stripped_lines取每个line,从words取每个word 并使用in检查该单词是否出现在该行中。你知道吗

4)a_line应该是number1 234,但我们只需要数字部分。所以split() 结果是

['number1','234']split()[1]表示索引1处的元素。(第二个元素)。你知道吗

5)还可以使用your_string.isdigit()检查字符串是否为数字

更新:自从您更新了您的问题和输入文件后,此操作正常:

import time

def isTimeFormat(input):
    try:
        time.strptime(input, '%H:%M')
        return True
    except ValueError:
        return False

with open("test.txt", "r") as f:
    lines = f.readlines()
    stripped_lines = [line.strip() for line in lines]

words = ["number1", "number2", "time"]
for a_line in stripped_lines:
    for word in words:
        if word in a_line:
            number = a_line.split()[-1] if (a_line.split()[-1].isdigit() or isTimeFormat(a_line.split()[-1]))  else a_line.split()[-2] 
            print(number)

为什么是isTimeFormat()函数?你知道吗

def isTimeFormat(input):
        try:
            time.strptime(input, '%H:%M')
            return True
        except ValueError:

检查3:44或4:55是时间格式。因为你也把它们当作价值观。 最终输出:

234
12
3:44

经过一番尝试和错误,我找到了如下解决方案。这是基于@s\u vishnu提供的答案

with open("test.txt", "r") as f:
    lines = f.readlines()
    stripped_lines = [line.strip() for line in lines]

    for item in stripped_lines:
        if "number1" in item:
            getval = item.split("actual ")[1].split(" ")[0]
            print getval

        if "number2" in item:
            getval2 = item.split("number2 ")[1].split(" ")[0]
            print getval2

        if "time" in item:
            getval3 = item.split("number3 ")[1].split(" ")[0]
            print getval3

输出

234
12
3:44

这样,我还可以做其他事情,例如将每个数据保存到数据库。你知道吗

我愿意接受任何进一步改进我的答案的建议。你知道吗

你想得太多了。假设第一行末尾没有这两个星号,并且希望打印出包含特定值的行,则可以逐行读取文件,检查所选值是否匹配,然后打印出最后一个值(空格和行尾之间的值)-根本不需要分析/拆分整行:

search_values = ["number1", "number2", "time"]  # values to search for

with open("test.txt", "r") as f:  # open your file
    for line in f:  # read it it line by line
        if any(value in line for value in search_values):  # check for search_values in line
            print(line[line.rfind(" ") + 1:].rstrip())  # print the last value after space

这将给你:

234
12
3:44

如果确实有星号,则必须更精确地定义文件格式,因为拆分不一定会产生所需的值。你知道吗

相关问题 更多 >