[英]Read lines from text file and if a specific word == 100, print the line
I have a text file that i want to read using python.我有一个要使用 python 阅读的文本文件。 The text file contains words and a value such as (rt= 3.878).
文本文件包含单词和一个值,例如 (rt= 3.878)。 I want to write a script using python to read the text file and if rt in line is == 3.878, print that line.
我想使用 python 编写一个脚本来读取文本文件,如果 rt in line 是 == 3.878,则打印该行。 I managed to write this piece of code so far.
到目前为止,我设法编写了这段代码。
with open ('/home/Desktop/hello.txt', 'r') as f:
f.readline()
for line in f:
if 'rt' in line == 3.878
print(line)
This code returns nothing.此代码不返回任何内容。 Could anyone kindly point out what I might be doing wrong?
谁能指出我可能做错了什么? thanks in advance!
提前致谢!
Apart from the syntax error of missing :
, if 'rt' in line == 3.878
is a bug.除了缺少
:
的语法错误, if 'rt' in line == 3.878
是一个错误。 The in
operator checks membership and returns True
or False
, which are 1 and 0 respective in int
context. in
运算符检查成员资格并返回True
或False
,它们在int
上下文中分别为 1 和 0 。 So ==
will produce unexpected result.所以
==
会产生意想不到的结果。
Anyway, things won't happen magically just because we want them to.无论如何,事情不会仅仅因为我们想要它们而神奇地发生。 Some processing need to be done.
需要做一些处理。 If
n
is the number you want to match and assuming the lines are like number = 1.234
如果
n
是您要匹配的数字并假设这些行类似于number = 1.234
if line.split("=")[-1].strip() == str(n): # don't float() the left side
# do something
As your file appears to have a very regular format, you could turn it into a dictionary:由于您的文件似乎具有非常规则的格式,您可以将其转换为字典:
with open('/home/Desktop/hello.txt') as f:
result = {k:float(v) for k,v in (line.split('=') for line in f)}
Then directly access the key you're interested in and check its value:然后直接访问您感兴趣的密钥并检查其值:
if result.get('rt') == 3.878:
print('rt=3.878')
You can quickly look up any key and its corresponding value without having to iterate through the whole file (or a saved sequence like a list
) again.您可以快速查找任何键及其对应的值,而无需再次遍历整个文件(或已保存的序列,如
list
)。
If your file can have multiple lines with the same key, you'll need to group their values into a list
, as dictionaries can't have duplicate keys.如果您的文件可以有多行具有相同的键,您需要将它们的值分组到一个
list
,因为字典不能有重复的键。 The common way to do this is with collections.defaultdict
:执行此操作的常用方法是使用
collections.defaultdict
:
import collections.defaultdict as dd
result = dd(list)
with open('/home/Desktop/hello.txt') as f:
for line in f:
k,v = line.split('=')
result[k].append(float(v)
You can then quickly look up any key and its corresponding values like you could with the basic dictionary.然后,您可以像使用基本字典一样快速查找任何键及其对应的值。 For example, you could print all values above a certain limit for a given key:
例如,您可以打印给定键的高于特定限制的所有值:
print(*(v for v in sorted(result.get('rt', '')) if v>100), sep='\n')
If you're really only interested in the rt
key and in checking that it has a value of 3.878
, you could do that in a few ways.如果您真的只对
rt
键感兴趣并检查它的值是否为3.878
,您可以通过几种方式做到这一点。
First, simply reading the whole file:首先,简单地读取整个文件:
with open('/home/Desktop/hello.txt') as f:
print('rt=3.878' in f.read())
Iterating through the file and stopping when the desired value is reached:遍历文件并在达到所需值时停止:
with open('/home/Desktop/hello.txt') as f:
for line in f:
if line.strip() == 'rt=3.878':
print(line)
break
Eagerly evaluating the contents of the file and checking for the desired value in there:急切地评估文件的内容并检查其中是否有所需的值:
with open('/home/Desktop/hello.txt') as f:
print('rt=3.878' in {line.strip() for line in f})
Creating a dictionary is the most versatile approach, and the one I'd recommend.创建字典是最通用的方法,也是我推荐的方法。 Iterating through the file and stopping when the desired value is reached is probably the best of the remaining approaches, as it will stop going through the file if and when it finds what you're looking for.
遍历文件并在达到所需值时停止可能是其余方法中最好的方法,因为它会在找到您要查找的内容时停止遍历文件。
Note that you could also find this content by simply opening the file in a text editor and searching for rt=3.878
with Ctrl + F .请注意,您也可以通过在文本编辑器中打开文件并使用Ctrl + F搜索
rt=3.878
来找到此内容。 The simple approach is often the best.简单的方法往往是最好的。
You can split each line on the =
delimiter and then compare the second index of the result, after casting it from string to a float:您可以在
=
分隔符上拆分每一行,然后在将结果从字符串转换为浮点数后比较结果的第二个索引:
with open("file.txt", "r") as f:
for line in f.readlines():
if float(line.split("=")[1]) == 3.878:
print line
This is what split
on line
looks like:这是
line
split
样子:
line = "rt=3.878"
print line.split("=")[0] # rt
print line.split("=")[1] # 3.878
print type(line.split("=")[1]) # type 'str'
print type(float(line.split("=")[1])) # type 'float'
Update Replace you loop with this to only consider lines where the first string is "rt" and not eg "ACCOUNT":更新用此替换循环以仅考虑第一个字符串为“rt”而不是例如“ACCOUNT”的行:
with open("file.txt", "r") as f:
for line in f.readlines():
if line.split("=")[0] == "rt":
if float(line.split("=")[1]) == 3.878:
print line
Well, may be:也许会:
with open ('/home/Desktop/hello.txt', 'r') as f:
f.readline()
for line in f:
if 'rt=3.878' in line:
print(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.