我有一个包含这些行的文本文件
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()
,但这次没有打印出任何内容。你知道吗
有人知道其他方法吗?最后,我想得到每一行的值,例如234
、12
和3:44
,并将其存储在数据库中。你知道吗
谢谢你的帮助。我真的很感激。你知道吗
解释如下:
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()
检查字符串是否为数字更新:自从您更新了您的问题和输入文件后,此操作正常:
为什么是
isTimeFormat()
函数?你知道吗检查3:44或4:55是时间格式。因为你也把它们当作价值观。 最终输出:
经过一番尝试和错误,我找到了如下解决方案。这是基于@s\u vishnu提供的答案
输出
这样,我还可以做其他事情,例如将每个数据保存到数据库。你知道吗
我愿意接受任何进一步改进我的答案的建议。你知道吗
你想得太多了。假设第一行末尾没有这两个星号,并且希望打印出包含特定值的行,则可以逐行读取文件,检查所选值是否匹配,然后打印出最后一个值(空格和行尾之间的值)-根本不需要分析/拆分整行:
这将给你:
如果确实有星号,则必须更精确地定义文件格式,因为拆分不一定会产生所需的值。你知道吗
相关问题 更多 >
编程相关推荐