簡體   English   中英

在Python的文本文件中搜索單詞

[英]Search for word in text file in Python

我有這個文本文件:

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

我需要找到與模型一致的線。

我的代碼:

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

這是輸出:

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

我只需要此行作為輸出:

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

我怎樣才能做到這一點?

只需替換行:

if term in line:

與線:

if line.startswith('model,'):

這取決於您的文件包含什么。 您的示例很簡單,但是我發現一些即時解決方案不會對您的代碼造成太大影響:

  1. 更換term = 'model'通過term = 'model,'這將只顯示你想要的行。

  2. 使用一些其他條件,例如“不得包含'name'

像這樣:

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

補充說明

  • 您可以使用startswith('somechars')來檢查字符串開頭的某些字符
  • 您需要在變量中分配strip()split(\\n)的結果,否則什么也不會發生。
  • 最好使用with關鍵字而不是打開/關閉文件
  • 總的來說,我認為對於這種類型的事情,最好使用正則表達式。 但是,正如Nander Speerstra的評論所指出的那樣,這可能很危險。

您可以按來分隔行,然后檢查第一個字段:

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