简体   繁体   English

在Python的文本文件中搜索单词

[英]Search for word in text file in Python

I have this text file: 我有这个文本文件:

MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075

I need to find the line with the model. 我需要找到与模型一致的线。

My code: 我的代码:

term = "model"
file = open('file.txt')
for line in file:
    line.strip().split('/n')
    if term in line:
        print line
file.close()

This is the output: 这是输出:

model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075

I need only this line as output: 我只需要此行作为输出:

 model,3,2016-07-30 15:39:59,075

How can I do this? 我怎样才能做到这一点?

Just replace the line: 只需替换行:

if term in line:

with line : 与线:

if line.startswith('model,'):

It depends on what your file contains. 这取决于您的文件包含什么。 Your example is quite light, but I see a few immediate solutions that don't change your code too much : 您的示例很简单,但是我发现一些即时解决方案不会对您的代码造成太大影响:

  1. Replace term = 'model' by term = 'model,' and this will only show the line you want. 更换term = 'model'通过term = 'model,'这将只显示你想要的行。

  2. Use some additional criteria, like "must not contain 'name' " : 使用一些其他条件,例如“不得包含'name'

Like this: 像这样:

term = 'model'
to_avoid = 'name'
with open('file.txt') as f:
    for line in file:
        line = line.strip().split('/n')
        if term in line and to_avoid not in line:
            print line

Additional remarks 补充说明

  • You could use startswith('somechars') to check for some characters at the beginning of a string 您可以使用startswith('somechars')来检查字符串开头的某些字符
  • You need to assign the result of strip() and split(\\n) in your variable, otherwise nothing happens. 您需要在变量中分配strip()split(\\n)的结果,否则什么也不会发生。
  • It's also better to use the keyword with instead of opening/closing files 最好使用with关键字而不是打开/关闭文件
  • In general, I think you'd be better served with regular expressions for that type of thing you're doing. 总的来说,我认为对于这种类型的事情,最好使用正则表达式。 However, as pointed out by Nander Speerstra's comment , this could be dangerous. 但是,正如Nander Speerstra的评论所指出的那样,这可能很危险。

You can split the line by , and check for the first field: 您可以按来分隔行,然后检查第一个字段:

term = "model"
file = open('file.txt')
for line in file:
    line = line.strip().split(',')  # <--- 
    if term == line[0]:             # <--- You can also stay with "if term in line:" if you doesn't care which field the "model" is. 
        print line
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM